Monday, 12 September 2016

COPY CONSTRUCTOR


Whenever you initialize an instance using values of instance of same type, the compiler will use the copy constructor. To put it in a simple way, a copy constructor used to initialize the the objects of its same type.It creates a reference object to it own class and uses their objects as it own parameters.

Syntax: class-name(class-name &object-name)




Example:

class A
{
                  int a;
                  int b;

public: 
                  A(int i,int j)    //parameterized constructor to initialize values
                  {
                     a=i;  
                     b=j;
                   }

                  A(A &obj)        //Copy constructor
                  {
                    cout<<"This is copy constructor\n";
                    a=obj.a;
                    b=obj.b;
                   }

                   void show()
                   {
                     cout<<"a= "<<a<<"\nb="<<b;
                   }
}; 

void main()
{
clrscr();

A obj1(2,3);  //Parameterized constructor called
A obj2(obj3);  //Copy constructor called

getch();
}

The above statement A obj2(obj3), copied the obj3 to obj2.


For More Help:



No comments:

Post a Comment