Shallow copy vs deep copy

shallow copy :

myStringD.str = myStringC.str; //copies just the //address 
myStringD.str = myStringC.str;

Note that both of the str pointers are pointing to the same location in memory. So, after one of the objects (myStringC) expires the destructor of that object free the memory using delete [], at the moment when the copied object(myStringD) try to free the memory, it’s already gone. This results in undefined behavior

void ShallowCopy(Copy &src, Copy &dest) {

dest.ptr = src.ptr; int dum = 1; }

The shallow copy may cause a lot of run-time errors, especially with the creation and deletion of object. Shallow copy should be used very carefully and only when a programmer really understands what he wants to do. In most cases, shallow copy is used when there is a need to pass information about a complex structure without actual duplication of data. We must also be careful with destruction of shallow copy. Actually, shallow copy should rarely be used.

deep copy : 

assign another address to the pointer , make a duplicate copy of the string. default behavior  for arrays is Deep copy

Example: Assignment overloading should be performed by our own assignment operator which makes a deep copy

void DeepCopy(Copy &src, Copy &dest) { dest.ptr = new char[strlen(src.ptr)+1];

memcpy(dest.ptr, src.ptr, strlen(src.ptr)+1);


Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.