Click here to Skip to main content
12,757,882 members (35,120 online)
Rate this:
Please Sign up or sign in to vote.
See more: C++
What is Shallow copy and Deep Cody?
Posted 8-Jan-13 20:29pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 2

When you copy an instance of class/structure by copying each member, in general case you won't get independent copies, because some member might be pointers, so copying a pointer will give your to instances of the class/structures with two pointers pointing to the same object. If you, say, access this object by dereferencing the pointer from source class/structure instance, the same object can be accessed from the copied instance, and appear modified.

That was about the shallow copy.

To make a deep copy (deep clone), you would need to recursively copy all objects pointed by member pointers by recreating them with the same members. This way, the actual depth of recursion and full copy operation may depend on the state of the object.

As standard C++ runtime lacks Reflection (I'm not talking about C++/CLI here; this is a different language), you cannot write one universal deep copy method.

One of the approaches is implementation of the deep copy interface (which can be an abstract class, without data with all pure virtual functions, or, rather one pure virtual function, like DeepCopy), and implementing this interface (generally, using weak (or strong) form of multiple inheritance) in the class/structure itself, overriding it in all inherited classes. The overridden deep copy function uses the base implementation, and so on.

prashant patil 4987 9-Jan-13 1:46am
my +5, nice...
Thank you, Prashant.
prashant patil 4987 9-Jan-13 1:49am
always welcome..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170217.1 | Last Updated 9 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100