Shallow and Deep Copy in CPP

Shallow and deep Copy in Cpp

What is Shallow and Deep Copy in CPP ?

Whenever we copy a data in C++ programming language, there may occur one of the two types of copying, i.e; shallow and deep copy. These two types of copying techniques plays an important role in C++ programming language, when it comes to copying of data. In this article, we will learn that what is shallow and deep copy and when and how to use them.

Difference between Shallow and Deep Copy

  • Shallow Copy – Shallow copy is the by default type of copy which occurs every time when we are copying some data in our program. In shallow copy if we copy a numeric type of data, than a new object is created and that numeric data is copied in the new object bit-by-bit. But, if the data that we want to copy is reference type, than no new object is created for that data, but the reference of the previous object is copied, without copying the referred object, this means that now we have two objects referring to the same data.
  • Deep Copy – Deep Copy is the copy technique which have to enforce manually from our end. Deep Copy works in the same way as Shallow Copy if we are copying a numeric data from one object to another, i.e;if we copy a numeric type of data, than a new object is created and that numeric data is copied in the new object bit-by-bit. But in deep copy if we want to copy a reference type of data, than a new copy of the referred object is performed. A deep copy of an object is a new object with entirely new instance variables, it does not share objects with the old. For doing a deep copy we have to overwrite the copy constructor.

CPP Code for how to overwrite Copy Constructor

#include<iostream> 
using namespace std; 
  
class PrepInsta 
{ 

    int a, b; 
public: 
    PrepInsta(int x, int y) 
    {
        a = x; 
        b = y;
    } 
  
    //Overriding Copy constructor 
    PrepInsta(const PrepInsta &p) 
    {
        a = p.a; 
        b = p.b; 
        
    } 
  
    int getA()
    { 
        return a;
    } 
    int getB()
    { 
        return b;
    } 
}; 
  
int main() 
{ 
    PrepInsta p1(21, 19); // calling the normal constructor
    PrepInsta p2 = p1; // calling copy constructor
  
    // printing the values, assigned by constructors
    cout << "p1.a = " << p1.getA() << "p1.b = " << p1.getB(); 
    cout << "p2.a = " << p2.getA() << "p2.b = " << p2.getB(); 
  
    return  0; 
}
Output
p1.a = 21   p1.b = 19
p2.a = 21   p2.b = 19