How many vptr will a object of class(uses single/multiple inheritance) have?

后端 未结 2 1121
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 14:57

How many vptrs are usually needed for a object whose clas( child ) has single inheritance with a base class which multiple inherits base1 and base2. What is the strategy for

2条回答
  •  悲&欢浪女
    2020-12-30 15:49

    The fine print

    Anything regarding vptr/vtable is not specified, so this is going to be compiler dependent for the fine details, but the simple cases are handled the same by almost every modern compiler (I write "almost" just in case).

    You have been warned.

    Object layout: non-virtual inheritance

    If you inherit from base classes, and they have a vptr, you naturally have as many inherited vptr in your class.

    The question is: When will the compiler add a vptr to a class that already has an inherited vptr?

    The compiler will try to avoid adding redundant vptr:

    struct B { 
        virtual ~B(); 
    };
    
    struct D : B { 
        virtual void foo(); 
    };
    

    Here B has a vptr, so D does not get its own vptr, it reuses the existing vptr; the vtable of B is extended with an entry for foo(). The vtable for D is "derived" from the vtable for B, pseudo-code:

    struct B_vtable { 
        typeinfo *info; // for typeid, dynamic_cast
        void (*destructor)(B*); 
    };
    
    struct D_vtable : B_vtable { 
        void (*foo)(D*); 
    };
    

    The fine print, again: this is a simplification of a real vtable, to get the idea.

    Virtual inheritance

    For non virtual single inheritance, there is almost no room for variation between implementations. For virtual inheritance, there are a lot more variations between compilers.

    struct B2 : virtual A {
    };
    

    There is a conversion from B2* to A*, so a B2 object must provide this functionality:

    • either with a A* member
    • either with an int member: offset_of_A_from_B2
    • either using its vptr, by storing offset_of_A_from_B2 in the vtable

    In general, a class will not reuse the vptr of its virtual base class (but it can in a very special case).

提交回复
热议问题