Copy Constructor


Sometimes it is required to copy the value of data member of one object into another object while creating it. This can be accomplished using the concept of copy constructor.
The constructor that accepts reference to the object as an argument is known as copy constructor.
Copy Constructor can be defined inside class as shown below:

     

Class Rectangle
{
int Height, Width;
public:
Rectangle (Rectangle &r)
{
Height = r.Height;
Width = r.Width;
}
}

Copy Constructor can be defined outside class as shown below:

Class Rectangle
{
int Height, Width;
public:
Rectangle (Rectangle &r);
}
Rectangle :: Rectangle (Rectangle &r)
{
Height = r.Height;
Width = r.Width;
}

In order to invoke copy constructor we need to pass object as an arguments while creating object. We can pass arguments using two different methods:
(1) Implicit:
Rectangle R2 (R1);
It will assign value of data member of object R1 into data member of object R2.
(2) Explicit:
Rectangle R2 = Rectangle (R1);
It will assign value of data member of object R1 into data member of object R2.

Download Projects


Download Programs