on Leave a Comment

C++ Deep Copy and Shallow Copy

When an object is created, compiler automatically creates a copy constructor and overloaded assignment (=) operator. We can also define copy constructor and overloaded assignment (=) operator in our class. When we assign a object to another object of same class, then either copy constructor or overloaded assignment operator can be called, depending upon where we assigning object. 

If we assigning a object to another object at the time of declaration, then copy constructor is called, for example,

class-name object1 = object2;

If we assigning a object to another object after the declaration, then overloaded assignment operator is called, for example,

class-name object1;
object1  = object2;

Shallow Copy

In shallow copy, an object copies all data and all resources from another object of same class. For example, if a class has two variables and one pointer, then if we assign object1 to object2 of that class, then content of two variables and one pointer is copied into object2. Now the problem is pointer of object2 is also pointing same memory block pointed by pointer of object1, which is disastrous.  

Example:

#include<iostream>
using namespace std;
class Example
{
private:
    int var1, var2;
    float *ptr;
public:
    Example()
    {
        ptr = new float;
    }
    Example(Example &o)
    {
        var1 = o.var1;
        var2 = o.var2;
        ptr = o.ptr;
    }
    void setData(int a, int b, float c)
    {
        var1 = a;
        var2 = b;
        *ptr = c;
    }
    void displayData()
    {
        cout<<endl<<var1;
        cout<<endl<<var2;
        cout<<endl<<*ptr;
    }

} ;
int main()
{
    Example obj1;
    obj1.setData(1, 2, 3.5);
    Example obj2 = obj1;
    obj2.displayData();
    return 0;
}

OUTPUT:

1
2
3.5

In this example, pointer of both obj1 and obj2 is pointing to same float variable. 

Deep Copy

In deep copy, content of an object is copied to other object of same class. But exact resources allocated to an object is not copied to other object. In deep copy, another resources are created and then assigning to other object. 

Example:

#include<iostream>
using namespace std;
class Example
{
private:
    int var1, var2;
    float *ptr;
public:
    Example()
    {
        ptr = new float;
    }
    Example(Example &o)
    {
        var1 = o.var1;
        var2 = o.var2;
        ptr = new float;
        *ptr = *(o.ptr);
    }
    void setData(int a, int b, float c)
    {
        var1 = a;
        var2 = b;
        *ptr = c;
    }
    void displayData()
    {
        cout<<endl<<var1;
        cout<<endl<<var2;
        cout<<endl<<*ptr;
    }

} ;
int main()
{
    Example obj1;
    obj1.setData(1, 2, 3.5);
    Example obj2 = obj1;
    obj2.displayData();
    return 0;
}

OUTPUT:

1
2
3.5

0 comments:

Post a Comment