“Ahhhhh, it’s time for C++,  and you know what that means,
A glass of wine, your favorite easy chair,  and of course Microsoft Visual Studio open in your Windows operating system.” -not the intro to “Smash” by the Offspring

What is the difference between a “deep copy” and a “shallow copy” in C++?

Is one better than the other, regarding copying objects?

I thought you would never ask. A shallow copy copies all the member values from one object to another. Great! But what if your member variables include pointers? You are going to run into some problems. To understand the difference between a shallow copy and a deep copy, let’s look at how and where issues can happen.

First, let me get my includes and namespace on:


Now some code:


This most basic C++ object, myObject. There is a single member variable, a pointer variable named ptr.

So let’s look at a shallow copy. Check out the following:


First, we created a method named shallowCopy, and then we pass in myObject as two separate reference parameters named src and dest(source and destination).  Two objects created.  All good, right?

Image result for NO meme

No. dest is pointing to src‘s location. This will lead to some problems with manipulating the data inside of shallow copies. When creating or deleting an object, a shallow copy may cause runtime errors. For example, if object src is deleted, runtime error. The best case for using shallow copies would be when the object is complex and you just need the state of the object at that instance in the program, basically something to reference and nothing more. If you start making changes to a copy of the object, you may be in for a runtime headache of epic proportions. So how can we get an accurate copy of an object, including references that don’t point to other objects?

So let’s look at making a deep copy:

Here is deepCopy with input parameters of references to myObject type named src and dest. The dest pointer is being casted as a char pointer in memory, with the same string length as src, but it exists on its own. Then copy the pointers using strcpy library function.

A deep copy does everything a shallow copy does, but also copies any pointer objects and dereferences them. So the dest and src pointers are no longer pointing to the same location in memory, but pointing at their own locations in memory. Deep copy should be used more often, especially when the size of the copied structure is large. Keep in mind they do cost a little more in memory, but deep copies are almost always the right way to go.

So, the main takeaway here: be sure your pointers are copied over when copying objects, make a deep copy.