对象内存布局 (10)

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

在对象内存布局 (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;
}

运行结果:

Derived对象的memory layout图解如下:

相关文章
|
存储 安全 算法
深入剖析JVM内存管理与对象创建原理
JVM内存管理,JVM运行时区域,直接内存,对象创建原理。
40 2
|
1月前
|
存储 算法 安全
【JVM】深入理解JVM对象内存分配方式
【JVM】深入理解JVM对象内存分配方式
29 0
|
6月前
|
存储 安全 程序员
浅谈内存管理及僵尸对象
浅谈内存管理及僵尸对象
33 0
|
1月前
|
Python
Python中如何判断两个对象的内存地址是否一致?
Python中如何判断两个对象的内存地址是否一致?
17 0
|
1月前
|
存储 安全 Java
【JVM】Java堆 :深入理解内存中的对象世界
【JVM】Java堆 :深入理解内存中的对象世界
53 0
|
2月前
|
存储 编译器 程序员
近4w字吐血整理!只要你认真看完【C++编程核心知识】分分钟吊打面试官(包含:内存、函数、引用、类与对象、文件操作)
近4w字吐血整理!只要你认真看完【C++编程核心知识】分分钟吊打面试官(包含:内存、函数、引用、类与对象、文件操作)
107 0
|
2月前
|
存储 缓存 算法
深入理解JVM - 对象分配内存
深入理解JVM - 对象分配内存
29 1
|
3月前
|
存储 缓存 算法
对象和数组并不是都是在堆上分配内存的
对象和数组并不是都是在堆上分配内存的
25 0
|
8月前
|
缓存 关系型数据库 MySQL
高性能内存对象缓存Memcached
高性能内存对象缓存Memcached案例
|
4月前
|
存储 Java
JVM(四):对象的内存布局
JVM(四):对象的内存布局