The Parameter of a Copy Constructor Must be Passed by Reference

The Parameter of a Copy Constructor Must be Passed by Reference

The canonical form of a copy constructor of a class C is:

   C::C(const C& rhs);

You can also declare the copy constructor’s parameter as follows:

   C::C(C& rhs); //no const, OK

That is, the const specifier is not mandatory. However, the parameter may not be passed by value:

   C::C(const C rhs); //Error: parameter passed by value

Can you see why the parameter must be passed by reference? Whenever you pass an object by value, you implicitly invoke its copy constructor, because the object passed is a copy of the original argument. The result is an infinite recursion: the copy constructor calls another copy constructor, which in turn calls another copy constructor and so on. To avoid this infinite recursion, C++ requires that a copy constructor’s parameter be passed by reference.

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist