#826 – Deep Copies

When making a copy of an object, you can either make a shallow copy or a deep copy.  As opposed to a shallow copy, a deep copy is one in which a copy is made not only of the top-level object, but of all the objects referenced by the original object.

During the copy process, whenever a reference to a child object is encountered, a new instance (or deep copy) of the child object is made.

For example, if a Dog object contains a reference to a DogCollar object and we make a deep copy, we get the following:

826-001

When doing a deep copy, a deep copy is typically made of all child objects in the object hierarchy.  For example, if the DogCollar instance had in turn referred to another object, a copy would have been made of that object.

#825 – Shallow Copies

When making a copy of an object, you can either make a shallow copy or a deep copy.  A shallow copy is one in which the exact values of all data members of the object are copied.  You can think of this as byte-for-byte copy of the original object.

With a shallow copy, reference-typed members are copied by copying the reference to the object, rather than by making a new copy of the child object.

For example, if a Dog object contains a reference to a DogCollar object and we make a shallow copy, we get the following:

825-001

The problem with a shallow copy is that the second object is now referencing the sub-objects that the first object pointed to.  In many cases, this may not be what you want.  In the example above, if we change the first dog’s collar, we also change the second dog’s collar.