memory layout of inherited class

后端 未结 5 578
不知归路
不知归路 2021-02-04 05:25

I\'m keen to know exactly how the classes will be arranged in memory esp. with inheritance and virtual functions.

I know that this is not defined by the c++ language st

5条回答
  •  生来不讨喜
    2021-02-04 05:38

    One way is to print out the offsets of all the members:

    class Parent{
    public:
        int a;
        int b;
    
        virtual void foo(){
            cout << "parent" << endl;
        }
    };
    
    class Child : public Parent{
    public:
        int c;
        int d;
    
        virtual void foo(){
            cout << "child" << endl;
        }
    };
    
    int main(){
    
        Parent p;
        Child c;
    
        p.foo();
        c.foo();
    
        cout << "Parent Offset a = " << (size_t)&p.a - (size_t)&p << endl;
        cout << "Parent Offset b = " << (size_t)&p.b - (size_t)&p << endl;
    
        cout << "Child Offset a = " << (size_t)&c.a - (size_t)&c << endl;
        cout << "Child Offset b = " << (size_t)&c.b - (size_t)&c << endl;
        cout << "Child Offset c = " << (size_t)&c.c - (size_t)&c << endl;
        cout << "Child Offset d = " << (size_t)&c.d - (size_t)&c << endl;
    
        system("pause");
    }
    

    Output:

    parent
    child
    Parent Offset a = 8
    Parent Offset b = 12
    Child Offset a = 8
    Child Offset b = 12
    Child Offset c = 16
    Child Offset d = 20
    

    So you can see all the offsets here. You'll notice that there's nothing at offset 0, as that is presumably where the pointer to the vtable goes.

    Also notice that the inherited members have the same offsets in both Child and Parent.

提交回复
热议问题