I wrote the following piece of code to test my understanding of virtual inheritance. Apparently, I still don't get it fully. Here is my code (followed by my question):
#include <iostream>
#include <vector>
using namespace std;
class Foo
{
public:
virtual void foo();
void foo2();
};
void Foo::foo()
{
cout << "In FOO - foo 1" << endl;
foo2();
}
void Foo::foo2()
{
cout << "In FOO - foo 2" << endl;
}
class Bar : public Foo
{
public:
void foo();
void foo2();
};
void Bar::foo()
{
cout << "In BAR - foo 1" << endl;
foo2();
}
void Bar::foo2()
{
cout << "In BAR - foo 2" << endl;
}
int main()
{
Foo* f = new Foo;
f->foo();
Foo* b = new Bar;
b->foo();
return 0;
}
This is my understanding:
The pointer f points to the base class Foo and f->foo()
calls foo()
in the base class which in turn calls foo2()
in the base class.
The pointer b is a base-class pointer but points to an object of the derived class Bar. Now, since foo()
is a virtual function, it calls foo()
of the derived class. Now foo()
(of the derived class) calls foo2()
. Since foo2()
is not a virtual function, I was expecting the base class foo2()
to get called. However I see that foo2()
of the derived class is getting called.
So, I was expecting this output:
In FOO - foo 1
In FOO - foo 2
In BAR - foo 1
In FOO - foo 2
but got this instead:
In FOO - foo 1
In FOO - foo 2
In BAR - foo 1
In BAR - foo 2
Why is this so? From what I understand, the vtable will have an entry only for foo()
and not for foo2()
. So, how is foo2()
of the derived class getting called?
This is my first post. Please excuse me if I have broken any posting guidelines. Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…