#include <iostream>
struct A {
void init()
{
internal_init();
}
virtual void internal_init()
{
std::cout << "internal of A" << std::endl;
}
};
struct B: public A {
void internal_init()
{
init();
std::cout << "internal of B" << std::endl;
}
};
int main(){
B instance;
std::cout << "internal of A" << std::endl;
instance.internal_init();
return 0;
}
First the program goes to B::internal_init()
as expected.
Then, to A::init()
(I guess since B derives from A , and B doesnt have any init()
).
Now what?
what internal_init()
it will choose? since it goes to B::internal_init()
,the program will go into and infinite loop, and I don't understand why.
- What really happens when I call
internal_init()
? - why it calls
internal_init()
of the "B part" of the instance? Is this about "virtual"? If so, how come? Virtual functions take place when we use polymorphism (which as far as a beginner like my self understands, it's working with pointers of a base class that point to a derived class objects).
internal_init
is not polymorphic. But withininit()
, the call is polymorphic because the (invisible)this
pointer is always a pointer... If you want to avoid this, you need to writeA::internal_init()
(thus forcing a non-polymorphic call) withininit
. – Effluent