ComputersConsumer ElectronicsCell PhonesHome Theater & AudioInternetGraphic Design & Video EditingIndustrial Technology

Deep Copy and Shallow Copy in C++ With Example

Updated on December 28, 2016
sirama profile image

I am a software engineer. I have been come across C++,MFC, .net technologies. I like playing video games & reading books.

1. Introduction

When we pass standard data types (int, float, bool 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 performs 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:

Source

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 hub. When the Hub 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();
Source

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:

Source

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:

Source

The entire code is shown below:

// TestIt.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class ShalloC
{
//Sample 01: Private Data Member
private:
	int * x;

public:
	//Sample 02: Constructor with single parameter
	ShalloC(int m)
	{
		x = new int;
		*x = m;
	}

	//Sample 08: Introduce Copy Constructor and perform Deep Copy
	ShalloC(const ShalloC& obj)
	{
		x = new int;
		*x = obj.GetX();
	}

	//Sample 03: Get and Set Functions
	int GetX() const
	{
		return *x;
	}
	void SetX(int m)
	{
		*x = m;
	}

	//Sample 04: Print Function
	void PrintX()
	{
		cout << "Int X=" << *x << endl;
	}

	//Sample 05: DeAllocate the heap
	~ShalloC()
	{
		delete x;
	}
};

int main()
{
	//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();

	//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();
}

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      DHiraj 5 months ago

      Nicest shallow copy and deep copy tutorial so far i found on internet. Just a case that when using with gcc on my redhat box, it gave double free of memory error while running then i worked it around by commenting the destructor and it worked fine. I dont know the reason, can you suggest possible flaw?