#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.
internal_init()
?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).Since instance
is a B
instance.internal_init();
Will call B
s internal_init()
. Then in internal_init()
you call init();
. Now member functions have an implicit parameter that is the this pointer.
So when we call A
's init()
the this pointer is actually a B
. In init()
we call internal_init();
using the this pointer to a B
. Since internal_init()
is virtual and we have a pointer to B
the virtual lookup mechanism will call B
's internal_init()
.
This then loops again and will eventually cause a segfault or stack overflow.
Firstly struct B
inherits all functions of struct A
because of struct B: public A
. The function internal_init
of A
is overridden in B
because you use the same function signature and the keyword virtual
in A
.
So now the calls are:
instance.internal_init();
which calls internal_init()
of B
, which calls A::init
, which calls B::internal_init()
, etc. until a segmentation fault is given.
To prevent this (and I think this is what you want), you can explicitly call the internal_init()
of A
in B
instead of calling init()
:
struct B: public A {
virtual void internal_init()
{
A::internal_init();
std::cout << "internal of B" << std::endl;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With