Cloning (programming): Difference between revisions

Content deleted Content added
thorough modifications, eliminated the use of memcpy in C++ (non-standard), juggled around examples, removed info that was incomplete paraphrasing of OOP article
m added syntax highlighting, changed typo '.' to a '->' in the c++ code
Line 5:
 
Copying primitive types in Java:
<source lang="java">
<pre>
int original = 42;
int copy = 0;
 
copy = original;
</presource>
 
Many OOP programming languages (including Java, [[C Sharp|C#]], [[D (programming language)|D]], [[ECMAScript]]) make use of object references. Object references, which are similar to pointers in other languages, allow for objects to be passed around by [[Pointer (computing)|address]] so that the whole object need not be copied.
 
A Java example, when "copying" an object using simple assignment:
<source lang="java">
<pre>
Object original = new Object();
Object copy = null;
 
copy = original; // does not copy object, only copies its reference
</presource>
The object is not duplicated, the variables 'original' and 'copy' are actually referring to the same object.
 
Line 27:
 
Cloning an object in Java:
<source lang="java">
<pre>
Object original = new Object();
Object copy = null;
 
copy = original.clone(); // duplicates the object and assigns the new reference to 'copy'
</presource>
 
C++ objects in general behave like primitive types, so to copy a C++ object one could use the '=' (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 [[Slicing]]). A method of avoiding slicing can be implementing a similar solution to the Java clone() method for your classes, and using pointers. (Note that there is no built in clone() method)
 
A C++ example of object cloning:
<source lang="cpp">
<pre>
Object original;
Object copy;
 
copy = original; // copies the contents of original into copy
</presource>
 
A C++ example of object cloning using pointers (avoids slicing):
<source lang="cpp">
<pre>
Object * original = new Object;
Object * copy = NULL;
 
copy = original.->clone(); // creates a copy of original and assigns its address to copy
</presource>
 
[[Category:Object-oriented programming]]