4

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

i know that a copy constructor must have a reference as a parameter, to avoid an 'infinite number of calls' to itself. my question is - why exactly that happens, what is the logic behind it?

CExample(const CExample& temp)
{
   length = temp.length;
}
Community
  • 1
  • 1
Anon
  • 1,274
  • 4
  • 17
  • 44

3 Answers3

6

assume your argument to the copy C'tor was passed by value, the first thing the C'tor would have done, was copying the argument [that's what every function, including constructors do with by-value arguments]. in order to do so, it would have to invoke the C'tor again, from the original to the local variable... [and over and over again...] which will eventually cause an infinite loop.

amit
  • 175,853
  • 27
  • 231
  • 333
  • "A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&,[...]" so anything else is not even a copy ctor... – PlasmaHH Aug 29 '11 at 13:56
  • @PlasmaHH: first word in my answer is 'assume'. the OP asks hyopthetical question, 'what if' when he asks 'what is the logic behind it' – amit Aug 29 '11 at 13:57
2

Copy constructors are called on some occasions in C++. One of them is when you have a function like

void f(CExample obj)
{
    // ...
}

In this case, when you make a call

CExample x;
f( x );

CExample::CExample gets called to construct obj from x.

In case you have the following signature

void f(CExample &obj)
{
     // ...
}

(note that obj is now passed by reference), the copy constructor CExample::CExample does not get called.

In the case your constructor accepts the object to be copied by value (as with the function f in the first example), compiler will have to call the copy constructor first in order to create a copy (as with the function f, again), but... oops, we have to call the copy constructor in order to call the copy constructor. This sounds bad, doesn't it?

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
1

See here

"It is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which ... "

Or put a different way a value parameter to the constructor would have to call the constructor to copy the value in the parameter. This new constructor would need to do the same - leading to infinite recursion!

Bob2Chiv
  • 1,858
  • 2
  • 19
  • 29