Size of virtual pointer-C++

前端 未结 6 738
迷失自我
迷失自我 2020-12-19 12:51

What is the size of virtual pointer(VPTR) for a virtual table in C++? Also this is not a homework question...just a question that came to my mind while I was reading a C++ b

6条回答
  •  太阳男子
    2020-12-19 13:35

    Note that in order to gracefully handle multiple inheritance, there can be more than one VPTR in an object, but in general each is likely to be a simple architecture dependent pointer.

    Try running something like this to see how your compiler lays things out:

    #include 
    using namespace std;
    
    struct Base
    {
        int B;
        virtual ~Base() {} 
    };
    
    struct Base2
    {
        int B2;
        virtual ~Base2() {} 
    };
    
    struct Derived : public Base, public Base2
    {
        int D;
    };
    
    int main(int argc, char* argv[])
    {
        cout << "Base:" << sizeof (Base) << endl;
        cout << "Base2:" << sizeof (Base2) << endl;
        cout << "Derived:" << sizeof (Derived) << endl;
    
        Derived *d = new Derived();
        cout << d << endl;
        cout << static_cast(d) << endl;
        cout << &(d->B) << endl;
        cout << static_cast(d) << endl;
        cout << &(d->B2) << endl;
        cout << &(d->D) << endl;
        delete d;
        return 0;
    }
    

    On my 32-bit compiler, this give 8 bytes for both Base classes, and 20 bytes for the Derived class (and double those values when compiled for 64 bits):

    4 bytes Derived/Base VPTR
    4 bytes int B
    4 bytes Derived/Base2 VPTR
    4 bytes int B2
    4 bytes int D
    

    You can see how by looking at the first 8 bytes, you can treat a Derived as a Base, and how by looking at the second 8 bytes, you can treat it as a Base2.

提交回复
热议问题