When an object is created from another object, the compiler performs shallow copy. The copy constructor provides a mechanims to perform deep copy.

  • Shallow Copy It is also called as field-by-field copy. In shallow copy the field values are copied as it is. Therefore if an object is pointing to a memory address to heap, the same address is copied. Therefore the source and destination object point to the same heap memory. If one of the object is modified then the effect is reflected on the other object too.

  • Deep Copy The references in the object are derefernced and thier values are copied to a seperate memory location.

Copy constructor is called when

  • a new object is created from an existing object.
  • an object of the class is returned by value.
  • an object of the class is passed (to a function) by value as an argument.
  • the compiler generates a temporary object
Object ob1;

Object ob2(ob1) // copy constructor called.

Object ob2 = ob1 // copy constructor called.

Example:

class Test {
    

    public:
    
    Test(const Test& ob) {
        size = ob.size;
        arr = new int [size];
        curr = 0;
        
        for(int i = 0; i < this->size; i++) {
            arr[i] = ob.arr[i];
            curr++;
        }
    }
    
    void insert(int x) {
        arr[curr] = x;
        curr++;
    }
    
    void print() {
        cout<<"Size: Address "<<&size<<" Value: "<<size<<endl;
        cout<<"Curr: Address "<<&curr<<" Value: "<<curr<<endl;
        
        for (int i = 0; i < size; i++) {
            cout<<arr + i<<" : " << *(arr + i) << endl;
        }
    }
    
    Test(int s) :size(s), curr(0) { arr = new int [s]; }
        
    
    private:
        int *arr;
        int size;
        int curr;
};


int main()
{
    Test t1(5);
    
    for( int i = 0; i < 5; i++) {
        t1.insert(i);
    }
    
    t1.print();
    cout<<endl;
    
    Test t2(5);
    t2 = t1;
    t2.print();
    cout<<endl;
    
    Test t3(t1);
    t3.print();
    
    return 0;
    
}