The constructor that creates a new class object from an existing object of the same class. A constructor can accept a reference to its own class as a parameter. Thus the constructor is declared as
Class A
{
public:
A (A&);
};
In this case, the constructor is called the copy constructor. A copy constructor is used to declare and initialize an object from another object.For example,the statement
Integer I2(I1);
Would define the object I2 and at a same time initialize it to the values of I1.Another form of this statement is
Integer I2=I1;
The process of initializing through a copy constructor is known as copy initialization.
A copy constructor takes a reference to an object of the same class as itself as an argument.
#include <iostream>
using namespace std;
class Code
{
int id;
public:
Code() {}
Code(int a) {
id=a;
}
Code(Code & x)
{
id=x.id;
}
void display(void)
{
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 << “\n id of B: ”;
B.display();
cout << “\n id of C: ”;
C.display();
cout << “\n id of D: ”;
D.display();
return 0;
}
A reference variable has been used as an argument to the copy constructor. The argument by value cannot be passed to a copy constructor. when no copy constructor is defined, the compiler supplies its own copy constructor. |