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 ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.