Copy Constructor and Assignment Operator
When an object is created from another object, the compiler performs shallow copy. The copy constructor provides a mechanims to perform deep copy.
-
Shallow Copy It is also called as field-by-field copy. In shallow copy the field values are copied as it is. Therefore if an object is pointing to a memory address to heap, the same address is copied. Therefore the source and destination object point to the same heap memory. If one of the object is modified then the effect is reflected on the other object too.
-
Deep Copy The references in the object are derefernced and thier values are copied to a seperate memory location.
Copy constructor is called when
- a new object is created from an existing object.
- an object of the class is returned by value.
- an object of the class is passed (to a function) by value as an argument.
- the compiler generates a temporary object
Example: