虚拟继承和内存布局

时间:2018-10-06 09:17:39

标签: inheritance virtual

  GCC/32Bit architecture  

class B
    {
        int x,y;
    };
    class D1: public virtual B
    {
        int z;
    };
    class D2; public virtual B
    {
        int z;
    public:
    virtual void func(){}
    };

    int main() {
        B b; D1 d1; D2 d2;
        cout<<sizeof(b)<<endl;
        cout<<sizeof(d1)<<endl;
        cout<<sizeof(d2)<<endl;
        return 0;
    }  

据我了解,             B有2个整数:8个字节             D1:B(B _vPtr),x,y,z => 16。             D2:B _vBase,VPTR,x,y => 16

       Ans i am getting is 8, 24, 24.
       What is the size of the class and how memory allocated for this classes. 
    How is Vptr and Vtable managed in these cases.

1 个答案:

答案 0 :(得分:0)

您正在使用什么编译器?视觉工作室? gcc?铛?什么目标体系结构(主要是32位或64位)? 您也可以查看Size of the classes in case of virtual inheritance

我不在看布局,但是我想说的是,指向父对象的指针与其实际数据之间存在填充,以使数据具有8字节对齐方式。这意味着4字节+ padding(4)+ 8字节父数据+本地数据+填充?

相关问题