views:

282

answers:

3

I was recently asked in an interview about the parameter for a copy constructor.
[Edited] As a designer of C++ language implementing copy constructor feature, why would you choose constant reference parameter over a const pointer to a const object.

I had a few ideas like since a pointer can be assigned to NULL which probably doesn't make sense (semantically) in a copy constructor and the fact that pointer variable is an independent object (which would probably not be good in terms of efficiency) whereas a reference is just an alias to the actual object (therefore a better way to pass the object).
Any other ideas?

+6  A: 

Because Stroustrup wanted classes to be like primitive-types. When you initialize an int variable:

int x = 5;
int y = x; // Why would you write int y = &x; ?

Passing constant pointer to constant object, is inconsistent with what C++ brought to C. classes in C++ are just User-Defined Types, if they don't work like primitive types then what are they?

Another example where programming in C++ would be miserable without references is operators overloading. Imagine you have to write:

myclass myobj1, myobj2, myobj3;
&myobj3 = &myobj1 + &myobj2;
AraK
very good point!
Ankur
+1  A: 

It's a syntactic convenience.

The most common use cases for when a copy constructor gets called is when a parameter is passed by value, or something is returned by value.

If the copy constructor had a parameter that was a pointer rather than a reference, you would need to apply the address-of operator in order to invoke the copy constructor, which would be awkward.

JohnMcG
A: 

I believe that important reason not to use pointers in copy constructors is how temporaries binded to rvalues. For pointers it will be possible to save pointer to temporary and use it later with undefined behavior, with references it is harder to store and use references, easier to use actual values.

Kirill V. Lyadvinsky