From the course: C++ Design Patterns: Creational

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Shallow vs. deep copies

Shallow vs. deep copies

- [Instructor] When cloning an object, all the members of one object is clone into the new one. Consider this Barn A object whose properties include a pointer to a Sheep object. When it's clone, all the member values are copied over, and that includes the pointer to the Sheep. The referred Sheep itself is not copied since Barn A's member is storing the pointer to the Sheep and not the Sheep object itself. Since both the original object and the cloned object, both point to the same Sheep object, when Sheep is updated both Barn A and Barn B get the updated value. This is referred to as a shallow copy. Only the members of an object are copied over to the new object and any referenced objects are not copied. If unaware of this characteristic, this could lead to some unexpected behaviors in an application. If I want the reference objects to be copied as well, this is called a deep copy. In this case, any reference objects…

Contents