What is a copy constructor ?What is the need for it ? What is the Shallow and deep copy ? When it gets called ? Write the signature ? What is the diff

Copy constructor invoked in following threee situations.

1. When a new object is created using existing object.

Ex. MyClass obj1;

MyClass obj2 = obj1;

2. When any object is passed by value.

Ex. void function( MyClass obj1) ;

MyClass obj2;

Function( obj2);

3. When any object returned by value.

Ex. MyClass function( ) {

MyClass obj2;

Return obj2;


Default Copy constructor performs the member by member copy or shallow copy

1. Shallow Copy : If user doesn't provides the Copy constructor , compiler provides one by default to the class. User needs to provide a Copy constructor for a class, if the class is having any memory allocations to member pointers.

Ex, class MyClass {

int *m_pData ;


MyClass ( Const MyClass & objectSource) {

m_pData = objectSource.m_pData;


Problems Caused: If there are any memory allocations and user is not providing the user defined Copy constructor , default Copy constructor will be called. It will do a member by member shallow copy. it means it will assign the same memory allocated inside one object to the other object. Both object will point to the same memory location. If one object modify values for its own use, same values will be available to another object. This turned into using wrong values for another object.

If such objects will going to be destroyed. For first object the memory will be freed and second object will again try to free the already freed memory by object one. This may corrupt the hip.

To avoid above scenario, User defined Copy constructor must be provided which provides the Deep Copy;

2. Deep Copy :

In deep copy first memory is allocated and then member values are copied.

MyClass ( Const MyClass & objectSource) {

m_pData = new int;

*m_pData = *(objectSource.m_pData);


Passng parameter(object) by value instead of refference.

If object is passed by value, again copy constructor will be called which will call again copy constructor. Thus the calling will be recursive and control will come back only after stack overflow.

Thus parameter to Copy constructor must be refference.

difference between copy constructor and overloaded assignment operator

Copy constructor first creates a new object and then copies the values from already created object to the new one.

Assignment operator copies values from one existing (already created) obect to another existing (already created) obect.

No comments: