Deep Copy Constructor in C++

Deep Copy Constructor in C++

1 min read

In C++, copy constructor mainly classify into two types shallow copy constructor and Deep copy constructor. In this article we are going to learn about deep copy constructor which is important topic of C++ and ask many times.

For copying everything from a constructor Deep constructor is used.

Usually when user wants to copy the allocated memory in heap using a pointer through constructor so pointer in copy constructor will not create a separate memory, it will point to previous one. This kind of constructor is known as Shallow copy constructor.

class Sample
{
private:
    int var;
    int *p;
public:
    Sample(int x) //parameterized constructor//
    {
        var = x;
        p = new int[var];
    }
    Sample(Sample &s) //Shallow copy constructor//
    {
        var = s.var;
        p = s.p;
    }
};

In above code, p in Sample(Sample &s) constructor will not allocate memory again. But as name suggest copy constructor means copying everything in a new variable or constructor. 

So here, we use Deep Copy Constructor to copy each and everything even to copy allocated memory. Pointer in Deep copy constructor will allocate memory every time when a new object is created.

class Sample
{
private:
    int var;
    int *p;
public:
    Sample(int x) 
    {
        var = x;
        p = new int[var];
    }
    Sample(Sample &s) //Deep copy constructor//
    {
        var = s.var;
        p = new int[var];
    }
};

so now, everything is copying from a constructor into new copy constructor and pointer p will allocate new memory every time whenever this constructor will be called. And also if you want to copy elements of array so you can do using for loop in Sample(Sample &s).  

Choose your Reaction!
Leave a Comment