top of page

difference between Shallow copy and deep copy in C++


Shallow copy:

Shallow copy means , new object created by simply copying the data of all variable of the original object.

Shallow copy also knows as member wise copy.

This means that C++ copies each member of the class individually (using the assignment operator for overloaded operator=, and direct initialization for the copy constructor).

when Shallow copy work well.

When classes are simple (e.g. do not contain any dynamically allocated memory ,pointer), this works very well.

Disadvantage of shallow copy.

when class contains any pointer then in case of shallow copy we copy data of all member variable simply so in this case we are copying same pointer (contains address of member variable) in both the object.

So it causes will create ambiguity and dangling pointer. because both objects keep reference to the same memory location, then change made by one will reflect those change in another object as well.

copy constructor, assignment operator provided by default compiler is based on shallow copy.


Deep copy:

deep copy allocates memory for the copy and then copies the actual value, so that the copy lives in distinct memory from the source. This way, the copy and source are distinct and will not affect each other in any way. Doing deep copies requires that we write our own copy constructors and overloaded assignment operators.


#include<iostream>
using namespace std;
class Base {
    private:
        int *ptr;
        int val;
    public:
        Base()
        {
            *ptr = 20;
            val = 15;
        }
        Base(const Base &obj)
        {
            int *ptr1 = new int();
            *ptr1 = *(obj.ptr);
            ptr = ptr1;
            val =obj.val;
        }
        void display()
        {
            cout << *ptr << val << endl;
        }
};

int main()
{
    Base obj;
    obj.display();
    Base cpy1 = obj;
    cpy1.display();
    return 0;
}

コメント


bottom of page