Cloning (programming): Difference between revisions

Content deleted Content added
Rescuing 1 sources and tagging 0 as dead. #IABot (v2.0beta15)
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags
Line 6:
 
Copying primitive types in Java or C++:
<sourcesyntaxhighlight lang="java">
int original = 42;
int copy = 0;
 
copy = original;
</syntaxhighlight>
</source>
 
Many OOP programming languages (including [[Java (programming language)|Java]], [[D (programming language)|D]], [[ECMAScript]], and [[C Sharp (programming language)|C#]]) make use of object references. Object references, which are similar to pointers in other languages, allow for objects to be passed around by [[Pointer (computer programming)|address]] so that the whole object need not be copied.
 
A Java example, when "copying" an object using simple assignment:
<sourcesyntaxhighlight lang="java">
Object original = new Object();
Object copy = null;
 
copy = original; // does not copy object but only its reference
</syntaxhighlight>
</source>
 
The object is not duplicated, the variables 'original' and 'copy' are actually referring to the same object. In C++, the equivalent code
 
<sourcesyntaxhighlight lang="c">
Object* original = new Object();
Object* copy = NULL;
copy = original;
</syntaxhighlight>
</source>
 
makes it clear that it is a ''pointer'' to the object being copied, not the object itself.
Line 38:
 
Cloning an object in Java:
<sourcesyntaxhighlight lang="java">
Object originalObj = new Object();
Object copyObj = null;
 
copyObj = originalObj.clone(); // duplicates the object and assigns the new reference to 'copyObj'
</syntaxhighlight>
</source>
 
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 [[Object slicing|slicing]]). A method of avoiding slicing can be implementing a similar solution to the Java <code>clone()</code> method for the classes and using pointers. (Note that there is no built-in <code>clone()</code> method)
 
A C++ example of object cloning:
<sourcesyntaxhighlight lang="cpp">
Object originalObj;
Object copyObj(originalObj); // creates a copy of originalObj named copyObj
</syntaxhighlight>
</source>
 
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>):
<sourcesyntaxhighlight lang="cpp">
Object* originalObj = new Object;
Object* copyObj = nullptr;
 
copyObj = new Object(*originalObj); // creates a copy of originalObj and assigns its address to copyObj
</syntaxhighlight>
</source>
 
==References==