Why Should the Copy Constructor Accept Its Parameter by Reference in C++

Why should the copy constructor accept its parameter by reference in C++?

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

Why can the copy constructor only take a reference argument?

just as the last answer

if you use the following statements:

Cents c1 ;
Cents c2(c1) ;

or pass your object to a function by value like this:

void Func (Cents c) {}

int main() {
Cents c1 ;
func (c1);
}

or use assignment operator to initialize your object:

Cents c2 = c1 ;

compiler will search for copy constructor and it will find that Cents( cents csource) (your proposed copy constructor)also pass the object by value. Technically to pass by value you ask the compiler to make a temporary copy of the object in the function body. So it is not logic to ask the copy constructor itself to call the copy constructor which would be a recursive call

Why is copy constructor not allowed pass by value?

Passing by value means that the parameter is copied into the function. That calls the copy constructor.

If your copy constructor parameter is pass-by-value... It would call itself... over and over again...

Why is the argument of the copy constructor a reference rather than a pointer?

There are many reasons:

  1. References cannot be NULL. OK, it's possible to create a NULL reference, but it's also possible to cast a std::vector<int>* into a std::vector<SomeType>*. That doesn't mean such a cast has defined behavior. And neither does creating a NULL reference. Pointers have defined behavior when set to NULL; references do not. References are therefore always expected to refer to actual objects.

  2. Variables and temporaries cannot be implicitly converted into pointers to their types. For obvious reasons. We don't want pointers to temporaries running around, which is why the standard expressly forbids doing it (at least when the compiler can tell you are doing it). But we are allowed to have references to them; these are implicitly created.

  3. Because of point number 2, using pointers rather than references would require every copy operation to use the address-of operator (&). Oh wait, the C++ committee foolishly allowed that to be overloaded. So any copy operation would need to actually use std::addressof, a C++11 feature, to get the address. So every copy would need to look like Type t{std::addressof(v)}; Or you could just use references.



Related Topics



Leave a reply



Submit