Copy Constructor in C++

What is copy constructor?

A copy constructor is used to declare and initialize an object from another object.”

“Constructor which accepts a reference to its own class as a parameter is called copy constructor.

Look at below code:

item t2(t1);
or
item t2=t1;
  1. The process of initializing through a copy constructor is known as copy initialization.
  2. Here, t2=t1 will not invoke copy constructor. t1 and t2 are objects, assigns the values of t1 to t2.
  3. A copy constructor takes a reference to an object of the same class as itself as an argument.

Example:

item(item &t1);

The above syntax shows the use of reference to pass object as argument.It is the real concept to show the use of copy constructor.

Example:

#include<iostream.h>
class code
{
    int id;
public
   code ( ) { } //constructor
   code (int a)   //constructor
   { 
     id=a; 
   } 
   code(code &x)
   {
     id=x.id;
   }
   void display( )
   { 
      cout<<id;
   }
};
int main( )
{
   code A(100);
   code B(A);
   code C=A;
   code D;
   D=A;
   cout<<” \n id of A :”; A.display( );
   cout<<” \nid of B :”; B.display( );
   cout<<” \n id of C:”; C.display( );
   cout<<” \n id of D:”; D.display( );
}
output:
id of A:100
id of B:100
id of C:100
id of D:100

Related posts