#825 – Shallow Copies
April 18, 2013 5 Comments
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:
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.