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

后端 未结 2 1051
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    Why do you care? The simple answer is enough, but I guess you want something more complete.

    This is not part of the standard, so any implementation is free to do as they wish, but a general rule of thumb is that in an implementation that uses virtual table pointers, as a zeroth approximation, for the dynamic dispatch you need at most as many pointers to virtual tables as there are classes that add a new virtual method to the hierarchy. (In some cases the virtual table can be extended, and the base and derived types share a single vptr)

    // some examples:
    struct a { void foo(); };           // no need for virtual table
    struct b : a { virtual foo1(); };   // need vtable, and vptr
    struct c : b { void bar(); };       // no extra virtual table, 1 vptr (b) suffices
    struct d : b { virtual bar(); };    // extra vtable, need b.vptr and d.vptr
    
    struct e : d, b {};                 // 3 vptr, 2 for the d subobject and one for
                                        // the additional b
    struct f : virtual b {};
    struct g : virtual b {};
    struct h : f, g {};                 // single vptr, only b needs vtable and
                                        // there is a single b
    

    Basically each subobject of a type that requires its own dynamic dispatch (cannot directly reuse the parents) would need its own virtual table and vptr.

    In reality compilers merge different vtables into a single vtable. When d adds a new virtual function over the set of functions in b, the compiler will merge the potential two tables into a single one by appending the new slots to the end of the vtable, so the vtable for d will be a extended version of the vtable for b with extra elements at the end maintaining binary compatibility (i.e. the d vtable can be interpreted as a b vtable to access the methods available in b), and the d object will have a single vptr.

    In the case of multiple inheritance things become a bit more complicated as each base needs to have the same layout as a subobject of the complete object than if it was a separate object, so there will be extra vptrs pointing to different regions in the complete object's vtable.

    Finally in the case of virtual inheritance things become even more complicated, and there might be multiple vtables for the same complete object with the vptr's being updated as construction/destruction evolves (vptr's are always updated as construction/destruction evolves, but without virtual inheritance the vptr will point to the base's vtables, while in the case of virtual inheritance there will be multiple vtables for the same type)

提交回复
热议问题