Copy constructor
A copy constructor is used when you pass an object by value (or return by value) or if you explicitly construct an object based on another object. The last two lines of the following both create a point object from another point object, and in both cases the copy constructor is called:
point p1(10, 10);
point p2(p1);
point p3 = p1;
The last line looks like it involves the assignment operator, but it actually calls the copy constructor. The copy constructor could be implemented like this:
class point
{
int x = 0;int y = 0;
public:
point(const point& rhs) : x(rhs.x), y(rhs.y) {}
};
The initialization accesses the private data members on another object (rhs). This is acceptable because the constructor parameter is the same type as the object being created. The copy operation may not be as simple as this. For example, if the class contains a data member that is a pointer, you will most likely want to copy the data that the pointer points to, and this will involve creating a new memory buffer in the new object.