对象内存布局 (10)

在对象内存布局 (9)基础上做些修改:派生类override基类的虚函数,即Base2 override Base1中声明的虚函数vfBase1(),Base3 override Base1中声明的虚函数vfBase1()和Base2中声明的虚函数vfBase2(), Derived override Base1中声明的虚函数vfBase1()、Base2中声明的虚函数vfBase2()和Base3中声明的虚函数vfBase3()。修改如下:

#include <iostream>
using 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  void vfBase1_1()
    {
        cout << "This is in Base2::vfBase1_1()" << endl;
    }
    inline virtual void vfBase2_1()
    {
        cout << "This is in Base2::vfBase2_1()" << endl;
    }
};
class Base3 : public Base2
{
public:
    int m_Base3;
    inline  void vfBase1_1()
    {
        cout << "This is in Base3::vfBase1_1()" << endl;
    }
    inline  void vfBase2_1()
    {
        cout << "This is in Base3::vfBase2_1()" << endl;
    }
    inline virtual void vfBase3_1()
    {
        cout << "This is in Base3::vfBase3_1()" << endl;
    }
};
class Derived : public Base3
{
public:
    int m_derived;
    inline  void vfBase1_1()
    {
        cout << "This is in Derived::vfBase1_1()" << endl;
    }
    inline  void vfBase2_1()
    {
        cout << "This is in Derived::vfBase2_1()" << endl;
    }
    inline  void vfBase3_1()
    {
        cout << "This is in Derived::vfBase3_1()" << endl;
    }
    inline virtual void fd()
    {
        cout << "This is in Derived::fd()" << endl;
    }
};
typedef void (*VFun)(void);
template<typename T>
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;
}

运行结果:

对象内存布局 (10)_第1张图片

Derived对象的memory layout图解如下:

对象内存布局 (10)_第2张图片

你可能感兴趣的:(内存)