Does every object of virtual class have a pointer to vtable?

后端 未结 9 923
借酒劲吻你
借酒劲吻你 2020-12-14 10:54

Does every object of virtual class have a pointer to vtable?

Or only the object of base class with virtual function has it?

Where did the vtable stored? code

9条回答
  •  无人及你
    2020-12-14 11:36

    Not necessarily

    Pretty much every object that has a virtual function will have one v-table pointer. There doesn't need to be a v-table pointer for each class that has a virtual function that the object derives from.

    New compilers that analyse the code sufficiently may be able to eliminate v-tables in some cases though.

    For example, in a simple case: if you only have one concrete implementation of an abstract base class, the compiler knows that it can change the virtual calls to be regular function calls because whenever the virtual function is called it will always resolve to the exact same function.

    Also, if there's only a couple of different concrete functions, the compiler may effectively change the call-site so that it uses an 'if' to select the right concrete function to call.

    So, in cases like this the v-table isn't needed and the objects might end up not have one.

提交回复
热议问题