Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz

Article

What is Copy Constructor in C++ , What is Shallow Copy Constructor and Deep Copy Constructor in C++ ?

7 min 55 sec read

Copy Constructor is used to copying the data of one object to another object. To understand the concept of copy constructor in-depth, we have written the C++ program below.

#include <iostream>
using namespace std;
class Dummy
{
   private:
      int a,b;
   public:
      void setData(int x, int y)
       {
        a = x;
        b = y;
        }

      void showData()
      {
            cout<< a << ""<< b;
       }
  };

int main()
{
   Dummy d1;
   d1.setData(3,4);
   
   Dummy d2 = d1;
   d2.showData();
return 0;
}

If you notice, in the given program there is One class named "Dummy" with two private data members a & b of integer type.  And two member functions setData() and showData(). Inside the main function, we have created an object of the Dummy class as d1. Then we used setData(3,4) member function which is used to set the value of a & b. Then in the next step, we created another object d2 of the Dummy class, and assigned object d1 to D2. Now, in this step what happened is, the default copy constructor is called which copied the contents of object d1 to the object d2 which we have then used to show the data using showData() member function with object d2.

Copy constructors are created by default by the compiler even if you dont write it. If we have added the copy constructor, it would be written like this,

#include <iostream>
using namespace std;
class Dummy
{
   private:
      int a,b;
   public:
      void setData(int x, int y)
       {
        a = x;
        b = y;
        }

      void showData()
      {
            cout<< a << ""<< b;
       }

//Copy Constructor
      Dummy(Dummy &d)
      { 
         a = d.a;
         b = d.b;
      }
  };

int main()
{
   Dummy d1;
   d1.setData(3,4);
   
   Dummy d2;
   d2 = d1;
   d2.showData();
return 0;
}

Now the thing is, copying takes place in two ways. Either you can pass it as a parameter or you can use it as an assignment way.

Pass as a parameter looks like this,

Dummy d2(d1);

Pass as an assignment to copy the objects looks like this,

Dummy d2;
 d2 = d1;

Now, There is this concept named Shallow Copy and Deep Copy.What exactly it is and how it works?

What is shallow copy constructor in C++?

The shallow copy you can think like its default nature of Copy Constructor. You dont have to write the explicit code for this. But, in the case of deep copy, you have to write the extra code to handle the copying of data elements. To understand the concept of deep copy practically, we start writing some code now.

#include <iostream>
using namespace std;
class Dummy
{
   private:
      int a,b,*p;
   public:
     Dummy()
     {
          p = new int;
     }
      void setData(int x, int y, int z)
       {
        a = x;
        b = y;
        }

      void showData()
      {
            cout<< a << "	"<< b;
       }

//Copy Constructor
      Dummy(Dummy &d)
      { 
         a = d.a;
         b = d.b;
          p = new int;
         *p = *(d.p); 
      }

   //Destructor
    ~Dummy()
     {
        delete p;
     }
  };

int main()
{
   Dummy d1;
   d1.setData(3,4,5);
   
   Dummy d2;
   d2 = d1;
   d2.showData();
return 0;
}

What is Deep copy constructor in C++?

In the case of Deep copy, we have added one more pointer variable p whose copy is created manually inside the copy constructor if you notice. Why we did this? 
Notice in the given figure, when we create an object D1 and assigned the values of a,b, and pointer variable p is holding the address of another memory location. As we know, the pointer points to some address.
So in the case of object d1, pointer variable p holds the address of another memory location that is outside that object and holding a value of 5.

Now when we create another object d2, the same copy will be created by the nature of the Copy constructor. While copying the constructor of object d2 to d1, the pointer variable address is also gets copied. This pointer in object d2 is also pointing to the same memory location where the pointer was pointing in the case of object d1.

So if we change the value of pointer variable p in object d1, it will also be changed in the case of object d2 also. But is not a good thing to change the value of memory locations. 
So to prevent this, we have created a separate copy of the pointer variable in object d2 which now points to a separate memory location. So even if we change it things will be in a better position. So, here we are not only copying the address of pointer variables but also the values it was pointing to. This is called deep copy practically in C++.


In simple words, you can think about both the concepts like this,

Shallow Copy Constructor

The shallow copy Constructor is used to point to the same object in a memory location. To understand this concept lets take one example. Suppose you and your friend are typing in the same Google Document in real-time. Both of you are working on it. In this case, if one friend changes the document it will be reflected for another friend also as they are working on the same document.  This is how you can understand the concept of a Shallow Copy constructor. It points to the same object in a memory location. If we change one object, the changes will be reflected in another one also.

 

Deep Copy Constructor

Deep copy constructor points to separate objects in the memory location.
To understand the concept of Deep Copy Constructor lets take one example. You have to submit an assignment tomorrow and you need to solve it today urgently. So you asked for help from your friend and copied the assignment into your book. Now, you found few spelling mistakes in it and modified them into your assignment while copying it. 
If you notice, changes you have made in your assignment will not be reflected in your friends book. As in this case, we have two separate books even though the answers were the same with little changes in one of the friends. This is how a deep copy constructor works.

 

Recommended Articles

1) What is Constructor in C++ ?

2) Question on C Program referencing the Increment and Decrement Operators concept asked in GATE CSE

3) Write C programs to implement i) strncpy(), ii) strstr() iii) strrchr library function by yourself

4) Write C program to insert a node after a given node in a linked list

5) Article on different storage classes in C.

6) C Tutorial on Calloc() vs malloc() functions is explained in depth in this article.

Did you found this article helpful?

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor