Deep vs Shallow Copy

Shallow Copy
Shallow Copy means that  C++ copy each member of the class individual using assignment operator. When classes are simple this work very well. However to when designing class with dynamic allocated memory this will cause us a lot of problems because the standard assignment operator just copy the address of the pointer. It does not allocate any memory or copy any of the contents that is being point to.

Deep Copy
The answer to the above problem is to do a deep copy on any pointer that is not null. A Deep copy duplicate the object or variable that is being point to  so that the destination receives it’s own copy of the object. This way the destination can do whatever it wants with its local copy without affecting the object that it was copied from.

The rule of thumb is that whenever you have a dynamic allocated object, you need to write your own copy constructor, assignment constructor and destructor. If not the default copy constructor, assignment constructor and destructor will be good enough.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: