假定多层继承的各类之间的关系如下图。假定派生类不override基类的虚函数,即Base2不override Base1中声明的虚函数vfBase1(),Base3不override Base2中声明的虚函数vfBase2(),Derived不override Base3中声明的虚函数vfBase3()。
代码如下
#includeusing namespace std;class Base1{public: int m_base1; inline virtual void vfBase1_1() { cout << "This is in Base1::vfBase1_1()" << endl; }};class Base2 : public Base1{public: int m_base2; inline virtual void vfBase2_1() { cout << "This is in Base2::vfBase2_1()" << endl; }};class Base3 : public Base2{public: int m_Base3; inline virtual void vfBase3_1() { cout << "This is in Base3::vfBase3_1()" << endl; }};class Derived : public Base3{public: int m_derived; inline virtual void fd() { cout << "This is in Derived::fd()" << endl; }};typedef void (*VFun)(void);template VFun virtualFunctionPointer(T* b, int i){ return (VFun)(*((int*)(*(int*)b) + i));}int main(void){ Derived d; cout << "The size of Derived object = \t" << sizeof(Derived) << endl; cout << endl; cout << "1st virtual function table: " << endl; int i = 0; while(virtualFunctionPointer(&d, i)) { VFun pVF = virtualFunctionPointer(&d, i++); pVF(); } return 0;}
运行结果:
Derived对象的memory layout图解如下:
(注意:单重继承只有一个虚函数表)