why improper copy constructor leads to infinite recusion - ?

P

puzzlecracker

B.S. page 271:
class complex {
double re, im;
...
public:
...

};

comlex::comple(complex c):re(c.re), im(c.im){} //error


call would have involve an infinite recursion. WHY?
 
R

Rade

B.S. page 271:
class complex {
double re, im;
...
public:
...

};

comlex::comple(complex c):re(c.re), im(c.im){} //error


call would have involve an infinite recursion. WHY?

Because if you, for example, have:

complex a(a1);

where a1 is an existing complex, that will involve three steps: (1)
copy-construction of the argument c, (2) actual copy-constructor call, (3)
destruction of c. The step (1) in turn calls the same copy constructor
recursively.

Rade
 
R

Rolf Magnus

puzzlecracker said:
B.S. page 271:
class complex {
double re, im;
...
public:
...

};

comlex::comple(complex c):re(c.re), im(c.im){} //error


call would have involve an infinite recursion. WHY?

Because the parameter is passed by value, which means it gets copied. For
that, the copy constructor is called. So for getting the parameter into the
copy constructor, the copy constructor must be called, which takes its
parameter by copy, so the copy constructor must be called, for which the
copy constructor must be called, since the parameter is passed by value.
But to call the copy constructor, a copy...

Hope you get the point ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top