Click here to Skip to main content
Rate this: bad
good
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
good
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.
 
—SA
  Permalink  
v2
Comments
prashant patil 4987 at 9-Jan-13 1:46am
   
my +5, nice...
Sergey Alexandrovich Kryukov at 9-Jan-13 1:49am
   
Thank you, Prashant.
—SA
prashant patil 4987 at 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
0 OriginalGriff 7,105
1 DamithSL 5,079
2 Maciej Los 4,866
3 Sergey Alexandrovich Kryukov 4,617
4 Kornfeld Eliyahu Peter 4,384


Advertise | Privacy | Mobile
Web01 | 2.8.141223.1 | Last Updated 9 Jan 2013
Copyright © CodeProject, 1999-2014
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