views:

563

answers:

4

Why copy constructor must be passed its parameter by reference?

+39  A: 

Because 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".)

GMan
Is there a reason it couldn't be pass-by-pointer to instance?
Barry Wark
Then it is no longer a copy constructor, but just a regular old constructor that happens to accept a pointer.
Dennis Zickefoose
wilhelmtell
Yes, that makes complete sense. Thanks.
Barry Wark
@Barry Wark: If the copy constructor took a pointer instead, how would calling a function look like? `void foo(X x);` `X x; foo( //!!` What about passing a temporary? `foo( //!!` But that would be different from what happens with built-in types (and structs in C).
visitor
+19  A: 

Because pass-by-value would invoke the copy constructor :)

Brian Roach
Excellent. Quite simply. ;)
wilhelmtell
+6  A: 

It would be infinitely recursive if you passed it in by value

Romain Hippeau
+5  A: 

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.

Potatoswatter
Compilers can happily spit out infinite recursion; I suspect this isn't a special case. However, the program is ill-formed if you declare a copy constructor with a non-reference parameter. So you're right that it shouldn't compile.
Dennis Zickefoose
@Dennis: I mean, if you attempted to compile such a program, the compiler would get stuck trying to generate the code. It would not generate a recursive function because the conundrum occurs before the function call, in the caller.
Potatoswatter
Either way, the program is ill formed whether you try to use it or not. Simply defining the constructor is enough to cause the compiler to yell at you.
Dennis Zickefoose
@Dennis: Indeed, although that is simply a rule.
Potatoswatter
+1 for quoting the standard _and_ explaining with reason.
wilhelmtell