What is Copy Constructors?

A copy constructor is used to declare and initialize an object from another object.
class integer
{
         private : int m;
         public: integer( integer & x)
//copy constructor
         { 
                  m = x.m; 
          }
};
integer a;
integer b(a);
//copy constructor called
integer c=a; //copy constructor called again

Let us an example:


#include<iostream.h>
class cse
{
         int count;
         public:cse(){ }
         cse(int a)
         { 

               count=a; 
          }
          cse(cse &);
          void display()
          { 

                   cout<<count<<"\n"; 
          }
};
cse :: cse(cse &x)
{
         count=x.count;

}
void main()
{
       cse x1(100);
       cse x2(x1);
       cse x3=x1;
       x1.display();
       x2.display();
       x3.display();
}


Sample Output:


Post a Comment

Previous Post Next Post