Thursday, February 17, 2011

Copy constructors


Copy constructors
Copy constructors are always used when the compiler has to create a temporary object of a class object. The copy constructors are used when the initialization of an object is to be done by another object of the same class.
The general format of the copy constructor is,
            class_name(class_name &object)
e.g.
     class copyConst
              {
                  …..
                 public:
                 copyConst(copyConst &ob);         
      };

Example:
class sample
{
      int id;
   public:
    sample (int x)          //constructor again defined with passing arguments
      {     id=x;      }

     sample(sample & obj)        //copy constructor
      {  id=obj.id; } //copy in the value

      void display()
      {  cout<<id;  }
};
void main()
{  sample ob1(100);     // object a is created and initialized
   sample ob2(ob1);     // copy constructor called
   sample ob3(ob2);     // copy constructor called again
   cout<<"\nId of ob1: ";
   ob1.display();
   cout<<"\nId of ob2: ";
   ob2.display();
   cout<<"\nId of ob3: ";
   ob3.display();
 }

Output:
Id of ob1: 100
Id of ob2: 100
Id of ob3: 100

No comments:

Post a Comment