Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Sep 3, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date