Supriya Ghosh (Editor)

Cloning (programming)

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

In computer science, cloning refers to the making of an exact copy of an object, frequently under the paradigm of instance-based programming, or object-oriented programming (OOP).

Contents

Shallow copies

In most programming languages (exceptions include: Ruby), primitive types such as double, float, int, long, etc. simply store their values somewhere in the computer's memory (often the call stack). By using simple assignment, you can copy the contents of the variable to another one:

Copying primitive types in Java or C++:

Many OOP programming languages (including Java, D, ECMAScript, and C#) make use of object references. Object references, which are similar to pointers in other languages, allow for objects to be passed around by address so that the whole object need not be copied.

A Java example, when "copying" an object using simple assignment:

The object is not duplicated, the variables 'original' and 'copy' are actually referring to the same object. In C++, the equivalent code

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 instead of just its reference is called cloning. In most languages, the language or libraries can facilitate some sort of cloning. In Java, the Object class contains the clone() method, which copies the object and returns a reference to that copied object. Since it is in the Object class, all classes defined in Java will have a clone method available to the programmer (although to function correctly it needs to be overridden at each level it is used).

Cloning an object in Java:

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 the classes, and using pointers. (Note that there is no built-in clone() method)

A C++ example of object cloning:

A C++ example of object cloning using pointers (to avoid slicing see ):

References

Cloning (programming) Wikipedia