#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:

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.

“if we change the first dog’s collar, we also change the second dog’s collar”

I don’t think that’s right. Unnless you meant if you change any of the details in DogCollar #1, then Dog #2 will display the same property values as Dog #1, but if you set Dog # 1’s collar to NewDogCollar , Dog # 2 will still have DogCollar # 1 as its collar. In other words, setting Dog # 1’s collar to a new collar doesn’t affect Dog #2 at all.