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

      Ramy Tanios 

      2 months ago

      the best

    • profile image

      SajjadNazari 

      2 months ago

      very clear and easy to undrestand

    • profile image

      CAD 

      3 months ago

      Nice explanation

    • profile image

      dshri 

      3 months ago

      the session is very helpful.

    • profile image

      DHiraj 

      14 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?

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)