Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy-constructor related question (native c++) [duplicate]

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;
}
like image 828
Vis Viva Avatar asked Jan 18 '23 21:01

Vis Viva


2 Answers

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.

like image 168
amit Avatar answered Jan 21 '23 09:01

amit


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?

like image 43
unkulunkulu Avatar answered Jan 21 '23 09:01

unkulunkulu