0% found this document useful (0 votes)
22 views18 pages

Deep Copy and Shallow Copy in Copy constructor

Uploaded by

Ajay Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
22 views18 pages

Deep Copy and Shallow Copy in Copy constructor

Uploaded by

Ajay Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

Deep Copy and Shallow Copy in C++ With Example

When we pass base data types (int, float etc.,) to a function a copy from the calling piece of
code to called function occurs. Now look at the below piece of code which does a simple
function call:

int AddNumbers(int loc_X, int loc_Y)


{
return (loc_X + loc_Y);
}
void main
{ int x = 5;
int y = 3;
int result = AddNumbers(x, y);
}

The copy I am taking occurs between x=>loc_X and y=>loc_Y. The content of variable x in main
function scope is copied to the variable loc_X, which is in the AddNumbers function scope.
This holds true for the next parameter loc_Y also. This copying is shown below:

OK. This is good for standard data types. A class can have one or more data members. How
the copy occurs between the data members is what we are going to deal with this article. When
the article progresses, I will explain Shallow Copy, Deep Copy and the need for our own copy
constructor.
2. ShalloC class

To demonstrate the need for the copy constructor, we will first define an example class. This
example class is ShalloC. This class contains only one integer pointer as private data member as
shown below:

//Sample 01: Private Data Member

private: int * x;
The constructor will create a memory location in a heap and copy the passed in value m to the
heap content. This code is shown below:

//Sample 02: Constructor with single parameter

ShalloC(int m){

x = new int;

*x = m;

}
The Get and Set functions are used to get the heap memory content value and Set the heap
memory content respectively. Below is the code that sets and gets the integer heap memory
value:

//Sample 03: Get and Set Functions


int GetX() const
{
return *x;
}
void SetX(int m)
{
*x = m;
}
Finally, there is a function to print the heap content value in the console window. The function is
shown below:
//Sample 04: Print Function
void PrintX(){
cout << "Int X=" << *x << endl;
}

Now you may get the idea of what the ShalloC class will do. At present it has a constructor that
creates a heap memory and in the destructor we clear the memory created as shown in the
below code:

//Sample 05: DeAllocate the heap

~ShalloC(){
delete x;
}

3. Shallow Copy vs. Deep Copy

In the Program main we created two Objects ob1 and ob2. The object ob2 is created using the
copy constructor. How? And where is the "copy constructor".? If you look at the
statement ShalloC ob2 = ob1 ; you clearly know that the ob2 is not yet created and in the
mean time ob1 is already created. Hence, a copy constructor is invoked. Even though the copy
constructor not implemented, the compiler will provide default copy constructor. Once both the
objects are created we print the values in ob1 and ob2.

//Sample 06: Create Object 1 and copy that to Object


2.// Print the data member for both Object 1 & 2.
ShalloC ob1(10);
ShalloC ob2 = ob1 ;
ob1.PrintX();
ob2.PrintX();
After printing the values in ob1 and ob2 we change the value of the object ob1’s data member
pointed value to 12. Then both the values of ob1 and ob2 are printed. The code and its output
are shown below:
//Sample 07: Change the Data member value of Object 1
// And print both Object 1 and Object 2
ob1.SetX(12);
ob1.PrintX();
ob2.PrintX();
The output shows value 12 for both ob1 and ob2. Surprisingly, we modified the data member of
the object ob1 only. Then, Why the changes are reflected on both the objects? This is what
called shallow copy induced by the compiler provided default constructor. To understand this
look at the below picture:

When object ob1 is created, the memory to store an integer is allocated in the heap. Let us
assume the heap memory location address is 0x100B. This address is what stored in the x.
Remember x is an integer pointer. The value stored in the pointer variable x is the address
0x100B and the content of the address 0x100B is value 10. In the example, we want to deal
with the content of the address 0x100B we use the pointer de-referencing like *x. The compiler
provided copy constructor copies the address stored in the ob1(x) to ob2 (x). After the copy,
both pointers in ob1 and ob2 points to the same object. So changing the 0x100B through
ob1.SetX(12) is reflected back in the ob2. Now you got how the result is printing 12 for both the
objects ob1 and ob2.

How do we avoid the above-shown problem? We should perform the deep copy by
implementing our own copy constructor. So a user defined copy constructor is required to avoid
the problem of shallow copy. Below is the copy constructor:
//Sample 08: Introduce Copy Constructor and perform Deep Copy
ShalloC(const ShalloC& obj)
{
x = new int;
*x = obj.GetX();
}

Once we inject this copy constructor to the ShalloC class, the x pointer in the object ob2 will not
point to the same heap location 0x100B. The statement x = new int; will create the new heap
location and then copies the value of obj content to new heap location. The output of the
program, after introducing our own copy constructor is shown below:

The entire code is shown below:


2. ShalloC ob1(10);
ShalloC ob2 = ob1 ;
ob1.PrintX();
ob2.PrintX();
//Sample 07: Change the Data member value of Object 1 // And
print both Object 1 and Object 2
ob1.SetX(12);
ob1.PrintX();
ob2.PrintX();
}

Geeks for geeks notes


In general, creating a copy of an object means to create an exact
replica of the object having the same literal value, data type, and
resources.
• Copy Constructor
• Default assignment operator
// Copy Constructor
Geeks Obj1(Obj);
or
Geeks Obj1 = Obj;
// Default assignment operator
Geeks Obj2;
Obj2 = Obj1;
Depending upon the resources like dynamic memory held by the
object, either we need to perform Shallow Copy or Deep Copy in
order to create a replica of the object. In general, if the variables of an
object have been dynamically allocated, then it is required to do a
Deep Copy in order to create a copy of the object.
Shallow Copy:
In shallow copy, an object is created by simply copying the data of all
variables of the original object. This works well if none of the variables
of the object are defined in the heap section of memory. If some
variables are dynamically allocated memory from heap section, then
the copied object variable will also reference the same memory
location.
This will create ambiguity and run-time errors, dangling pointer. Since
both objects will reference to the same memory location, then change
made by one will reflect those change in another object as well. Since
we wanted to create a replica of the object, this purpose will not be
filled by Shallow copy.
Note: C++ compiler implicitly creates a copy constructor and overloads
assignment operator in order to perform shallow copy at compile time.

Shallow Copy of object if some variables are defined in heap memory,


then:

Below is the implementation of the above approach:

• C++
// C++ program for the above approach

#include <iostream>

using namespace std;

// Box Class

class box {

private:

int length;

int breadth;

int height;

public:

// Function that sets the dimensions

void set_dimensions(int length1, int breadth1,

int height1)

length = length1;
breadth = breadth1;

height = height1;

// Function to display the dimensions

// of the Box object

void show_data()

cout << " Length = " << length

<< "\n Breadth = " << breadth

<< "\n Height = " << height

<< endl;

};

// Driver Code

int main()

{
// Object of class Box

box B1, B3;

// Set dimensions of Box B1

B1.set_dimensions(14, 12, 16);

B1.show_data();

// When copying the data of object

// at the time of initialization

// then copy is made through

// COPY CONSTRUCTOR

box B2 = B1;

B2.show_data();

// When copying the data of object

// after initialization then the

// copy is done through DEFAULT


// ASSIGNMENT OPERATOR

B3 = B1;

B3.show_data();

return 0;

Output:
Length = 14
Breadth = 12
Height = 16
Length = 14
Breadth = 12
Height = 16
Length = 14
Breadth = 12
Height = 16

Deep Copy:
In Deep copy, an object is created by copying data of all variables, and
it also allocates similar memory resources with the same value to the
object. In order to perform Deep copy, we need to explicitly define the
copy constructor and assign dynamic memory as well, if required. Also,
it is required to dynamically allocate memory to the variables in the
other constructors, as well.
Below is the implementation of the above approach:

• C++

// C++ program to implement the

// deep copy

#include <iostream>

using namespace std;

// Box Class

class box {
private:

int length;

int* breadth;

int height;

public:

// Constructor

box()

breadth = new int;

// Function to set the dimensions

// of the Box

void set_dimension(int len, int brea,

int heig)

length = len;
*breadth = brea;

height = heig;

// Function to show the dimensions

// of the Box

void show_data()

cout << " Length = " << length

<< "\n Breadth = " << *breadth

<< "\n Height = " << height

<< endl;

// Parameterized Constructors for

// for implementing deep copy

box(box& sample)

{
length = sample.length;

breadth = new int;

*breadth = *(sample.breadth);

height = sample.height;

// Destructors

~box()

delete breadth;

};

// Driver Code

int main()

// Object of class first

box first;
// Set the dimensions

first.set_dimension(12, 14, 16);

// Display the dimensions

first.show_data();

// When the data will be copied then

// all the resources will also get

// allocated to the new object

box second = first;

// Display the dimensions

second.show_data();

return 0;

Output:
Length = 12
Breadth = 14
Height = 16
Length = 12
Breadth = 14
Height = 16

Let us see the differences in a tabular form -:


Shallow Copy Deep copy

When we create a copy of object When we create an object by copying data of


by copying data of all member another object along with the values of
variables as it is, then it is called memory resources that reside outside the
1. shallow copy object, then it is called a deep copy

A shallow copy of an object


copies all of the member field Deep copy is performed by implementing our
2. values. own copy constructor.

It copies all fields, and makes copies of


In shallow copy, the two objects dynamically allocated memory pointed to by
3. are not independent the fields

If we do not create the deep copy in a rightful


It also creates a copy of the way then the copy will point to the original,
4. dynamically allocated objects with disastrous consequences.

You might also like