Wednesday 22 February 2012

When are copy constructors called? | Constructor in C++

A copy constructor is defined by the programmer or by compiler itself. A call to copy constructor is embedded under the following three conditions:
1. When an object is created and at the same time equated to some other existing object.
 For example:
A A1; //default constructor called.
A A2=A1; //copy constructor called.
(or)
A A2(A1) //copy constructor called.
(or)
A *Aptr= new A(A1); //copy constructor called.
2. When an object is created without having the reference of the argument, then the copy constructor is called by default for the argument object.
For example:
A A1;
xyz(A1);
void xyz(A A2)
{
//defination of xyz()
}
3. When an object is created and at the same time equated to a call to a function that returns an object.
For example:
A xyz();
{
A A1; //remaining defination of xyz();
return A1;
}
A A2=xyz();