>

what is the purpose of copy constructor

copy constructor is a constructor which is implicitly provided by compiler and is used to create new object as copy of existing object of same class.

If an user writes his own copy constructor then compiler does not create copy constructor.So there is always one copy constructor which is available to the program which is either of compiler provided or user defined.

A copy constructor can have more than one argument but except first argument other argument must have default values.

Lets take an example  of Class A.

class A{

public:

//All examples mentioned below is an example of copy constructor

A(const A& a);

A(A& a);

A(volatile A&   a);

A(const volatile A&  a);

A(A&  a,double  x=1.0);

A(const A& a,int z=1,  double m=3.0,  char n=’h’);

};

When we want to create and initialize an object with object of same class we use copy constructor,

Ways  to  invoke copy constructor

1.A z;           //default constructor invoked

A x(z);     //copy constructor is invoked

 

2.A x=A( );    //copy constructor invoked

Above call is valid if copy constructor is defined as   A(const A & a) as when right hand side of above line A() is invoked, default constructor is called and creates temporary object then copy constructor is invoked to copy to left hand side object x.As temporary is const so copy constructor A(const A &) is invoked.

3.const A z;

A x=z;

Above call is valid if copy constructor takes constant argument like A(const A&  a)

4.A z;

A x=z;

valid if any copy constructor is defined,Default copy constructor provided by compiler can also take care of this.

Copy constructor  is always defined with reference to Class and not the instance of the class so below defined statements are invalid as  call to below functions will lead recursive construction of objects.

A(A a);

A(const A a);

In which cases copy constructor is called?

1.When an object is thrown in try block.

2.When object is caught in catch block.

3.When an object is returned by value.

4.When object is passed as value to a function. Ex – func(a)

5.When object is used in initialization  list.

Leave a Reply