Content deleted Content added
m Reverted edits by 82.5.55.147 (talk) to last version by StuartMurray |
|||
(31 intermediate revisions by 27 users not shown) | |||
Line 1:
{{refimprove|date=August 2015}}
In [[computer science]], '''
==Shallow copies==
In most programming languages (exceptions include
Copying primitive types in Java or [[C++]]:
<
int original = 42;
int copy = 0;
copy = original;
</syntaxhighlight>
Many OOP programming languages (including
A Java example, when "copying" an object using simple assignment:
<
Object original = new Object();
Object copy = null;
copy = original; // does not copy object
</syntaxhighlight>
The object is not duplicated, the variables 'original' and 'copy' are actually referring to the same object.▼
▲The object is not duplicated, the variables 'original' and 'copy' are actually referring to the same object. In C++, the equivalent code
<syntaxhighlight lang="c">
copy = original;
</syntaxhighlight>
makes it clear that it is a ''pointer'' to the object being copied, not the object itself.
==Cloning==
The process of actually making another exact replica of the object
Cloning an object in Java:
<
Object
Object
</syntaxhighlight>→
C++ objects in general behave like primitive types, so to copy a C++ object one could use the '<code>=</code>' (assignment) operator. There is a default assignment operator provided for all classes, but its effect may be altered through the use of [[operator overloading]]. There are dangers when using this technique (see [[
A C++ example of object cloning:
<
Object
Object copyObj(originalObj); // creates a copy of originalObj named copyObj
</syntaxhighlight>
A C++ example of object cloning using pointers (to avoid slicing see<ref>See Q&A at [http://en.allexperts.com/q/C-1040/constructor-virtual.htm en.allexperts.com] {{Webarchive|url=https://web.archive.org/web/20090718130949/http://en.allexperts.com/q/C-1040/constructor-virtual.htm |date=2009-07-18 }}</ref>):
Object* originalObj = new Object;
Object* copyObj = nullptr;
</syntaxhighlight>
▲<source lang="cpp">
▲Object * original = new Object;
▲Object * copy = NULL;
==References==
▲copy = original->clone(); // creates a copy of original and assigns its address to copy
{{reflist}}
<!--Categories-->
[[Category:Object-oriented programming]]
|