Cloning an Object (Deep Copy)
You want to clone an object with all its sub-objects.
The difference between copying an object through assignment and through this clone-function is how they handle references. The assignment only copies the object's reference, whereas the clone-function creates a complete new object by
- creating a new object like the source object,
- copying all attributes form the source object to the new object and
- repeating these steps for all sub-objects by calling the clone-function recursively.
Example of an assignment copy:
As you can see, when you change
y after the copy, you also change