menu

hjk41的日志

Avatar

More Effective C++ 24: Understand the costs of virtual functions, multiple inheritance...

Virtual functions are generally implemented by using virtual tables and virtual table pointers, which are called vtbl and vptr for short.
All pointers to virtual functions are placed in vtbl, and vptr points to the head of vtbl. Every class has only one vtbl, and every object has a vptr given that there is no multiple inheritance. For a call to a vitual function, the compiler actually generate code like this:


Object * obj;
(* obj->vtbl[i]) (parameters);


vtbl is an array of function pointers, and the index i indicates which virtual function are called. As we can see, the actual costs of virtual functions are small.

However, when multiple inhertance enters the picture, the problem gets more complicated. The derived class must have all the virtual pointers that base classes have. Hence it will be more complicated to get the pointer to the virtual function called.

Moreover, virtual functions should not be declared inline. This rule have been explained in the former items.

Finally, RTTI is implemented through vtbl. So if there is no virtual function in a class, the RTTI is not guranteed to give correct result.

评论已关闭