Click here to Skip to main content
15,885,044 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is Shallow copy and Deep Cody?
Posted

1 solution

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.

—SA
 
Share this answer
 
v2
Comments
prashant patil 4987 9-Jan-13 1:46am    
my +5, nice...
Sergey Alexandrovich Kryukov 9-Jan-13 1:49am    
Thank you, Prashant.
—SA
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900