Copy constructor:
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one. If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor.
Example:
#include<iostream.h>
class point
{
private:
int x, y;
public:
point(int x1, int y1)
{
x = x1;
y = y1;
}
// copy constructor
point(point &p2)
{
x = p2.x;
y = p2.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
point p1(10, 15); // Normal constructor is called here
point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout<< "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout<< "\np2.x = " << p2.getX() << ", p2.y = " <<
p2.getY();
return 0;
}