Saturday, 2 October 2010

Copy Constructor



Copy Constructor

Copy constructor is a special type of parameterized constructor. As its name implies, it copies one object to another. It is called when as object is created and equated to an existing object at the same time. The copy constructor is called for the object being created. The pre existing object is passed as a parameter to it. The Copy constructor member-wise copies the object passed as a parameter to it into the object for which it is called.

If we do not define copy constructor for a class, the compiler creates it for us.
The following examples make these things clear.

Case1:

Distance d1;        // Distance is a class. Zero-argument or default constructor is called.
Distance d2=d1;  // Copy constructor is called.



Case2:

Distance d1;          //  Distance is a class. Zero-argument or default constructor is called.
Distance d2(d1);   // copy constructor is called since d1 is passed as a parameter while creating
                                 the object d2.


Case3:

Distance d1;  // Distance is a class. d1 an object of Distance class is created.
void abc(Distance);  // It is a prototype of abc() function. It takes distance object as a parameter.

void abc(Distance d2)   // Here copy constructor is called.
{

 //some function body
}

Case4:

Distance abc()   // the return type of abc() function is an object of type distance.
{
   //some function body.
}

Distance d2 = abc();  // Here copy constructor is called.

EXAMPLE:
class E
{
int a;
public:
E ( );
E (int a);
void put( );
};

E::E()
{
a=0;
}

E::E(int a)
{
this  -> a = a
}

void E( ) : :put( )
{
cout<<”a=”<<a<<endl;
}
void main()
{
Clrscr( );
E obj;
obj.put();
obj =E(7);  //copy constructor will be called
Obj.put ( );
E,obj1=E(obj); //explicit call to copy constructor
E.obj2(obj1);     //implicit call to copy constructor
obj1.put();
obj2.put();
}


No comments:

Post a Comment