CConstructor Infinite Recursion!
Hi all!,
so I have finally reached the stage where I am "forced" to learn about Copy constructor. And i understand the basics of it.
When we pass an object by value as parameter, the Copy Constructor is called.
What I don't get is...how does it lead to an infinite recursion? Whereas pass by reference
doesn't ?
Code:
class Dog
{
Dog(){}
Dog(const Dog &dog)
{
//safe
}
Dog(Dog dog)
{
height=dog.height; //...
//leads to infinite recursion. But I don't see how!
}
}
how does the pass by copy lead to an infinite recursion ?
The copy constructor copies the all the member variables, does it copy the function code as well? , it copies them and pushes it onto the stack and it should stop.
Why would the copy constructor need to be called again, and again?
Can you please explain this to a noob.
Thanks.
Hey, so I wrote the idea down on paper.
so I think maybe I can understand what you meant by infinite recursion. If i go back to function call basics.
Code:
void foo(int a) ;
main()
{
foo(10) ;
}
Steps
1. main invokes the foo function.
2. the compiler/OS sets about to make a copy of 10 and assigns a the copied value.
3. function call ends.
now if i apply that basic concept, then the theory of infinite recursion makes sense
Code:
class A
{
A(A a)
{
// we assume it will compile
}
} ;
main()
{
A a ;
B b(a) ;
}
Steps
"B b(a)" naturally will invoke a function call.
1. Copy constructor is invoked. We've already defined one, so compiler issues that.
2. Compiler/OS (i'm not sure which, but I assume it is the OS, makes more sense) proceeds to make a copy of the object in the parameter.
But wait it is an object, and what makes copies of object? A copy constructor! Copy constructor is invoked.
3. Compiler proceeds to make a copy of the parameter. Hold on, it is an object. What makes copies of objects? A copy constructor! We've defined one. and so it goes on.
Infinite recursion...
But for pass by reference
Code:
class A
{
A(A &a)
{
// we assume it will compile
}
} ;
main()
{
A a ;
B b(a) ;
}
Steps
1. Copy constructor is invoked.
2. Compiler proceeds to make copy of parameter.
3. It is not a object, but a reference to the object.
4. The compiler makes a copy of the address and stores the address to the copy constructor parameter. The compiler automatically dereferences it for us, which makes all the difference between references and compiler. (Simply the compiler makes a reference to the constructor parameter)
5. Copy Constructor exits.
No infinite recursion.
So I was going through all this on paper, to really "see" what was happening. and I think the "algorithm" of what happens might be what you meant.
Going through it feels correct and makes sense.
Is it correct?
Thanks
Why does STL invoke copy constructor.
Em. Does anyone know why a pushing an object into a list invokes the copy constructor?
I just had a glance at the api and noticed it takes a reference to an object. So it shouldn't invoke it, but it does?