2

Possible Duplicate:
Why should the copy constructor accept its parameter by reference in C++?
Why is copy constructor not allowed pass by value?

I am reading the lecture notes for my class on C++. In the notes they say the copy constructor signature for a class is

MyClass(MyClass &other)

and

MyClass(MyClass other)

won't work. Why is that?

Thank you!

Community
  • 1
  • 1
i love stackoverflow
  • 1,555
  • 3
  • 12
  • 24

5 Answers5

15

Because MyClass(MyClass other) is passing the parameter by value, which itself requires a copy to be created. This would lead to an infinite loop (terminated only when your stack overflows).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

This is because in order to pass an instance of MyClass other to a constructor with the second signature the constructor would need to call itself, resulting in infinite recustion leading to stack overflow.

Try it out, this is a very instructive exercise!

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

MyClass(MyClass other) is passing other by copy, which would invoke the copy constructor, which you are defining, thus you would end up with infinite recursion.

Alan
  • 45,915
  • 17
  • 113
  • 134
1

MyClass(MyClass other) is already creating a copy of other because you are passing the parameter other as variable not as reference, so the copy constructor in this case would be meaningless

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
1

Valid copy constructor signatures are

MyClass(MyClass &other) MyClass(const MyClass &other) MyClass(MyClass const &other)

In C++ all function parameters are passed by value. This means that if you'll pass other by value it will be destroyed after the function call operator finishes. Moreover, in case of copy constructor infinite loop of copy constructor execution will be met. So copy constructor parameter is always passed by reference.

nickolay
  • 3,643
  • 3
  • 32
  • 40
  • The second two are identical... – Oliver Charlesworth Jan 06 '12 at 17:45
  • Yep. They're identical from the compiler POV, but not from the human one :) So, let them both be for the newcomers eyes. – nickolay Jan 06 '12 at 17:47
  • 1
    @badatmath: If a variable or reference is `const`, it cannot be used to change a value. In this case, the `const` means that the function will not modify `other`. (As in most things in C++, there's ways around this, but let's not worry about them now.) – David Thornley Jan 06 '12 at 18:28