Why copy constructor must be passed its parameter by reference?
views:
563answers:
4Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to need to make a new value, so we call the copy constructor, and so on...
(You would have infinite recursion because "to make a copy, you need to make a copy".)
It would be infinitely recursive if you passed it in by value
The alternative to pass-by-reference is pass-by-value. Pass-by-value is really pass-by-copy. The copy constructor is needed to make a copy.
If you had to make a copy just to call the copy constructor, it would be a conundrum.
(I think the infinite recursion would occur in the compiler and you'd never actually get such a program.)
Besides rational reasons, it's forbidden by the standard in §12.8/3:
A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv- qualified) X and either there are no other parameters or else all other parameters have default arguments.