c++ - Does the cost of virtual functions increase with the number of classes in the inheritance tree? -


like title says, e.g. having 8 derived classes virtual functions affect performances more having 2 derived classes? , if so, difference negligible?

and multiple inheritance (non virtual inheritance)?

thanks in advance.

the common implementation of dynamic dispatch in c++ means of virtual table, array of pointers functions, 1 each virtual function in type. length of inheritance chain not matter, since vtable holds 1 pointer, of final overrider particular function in complete object. single indirection whether final overrider in base or hundred levels it.

multiple inheritance can have small impact in performance, amount of depend on actual implementation, independent of number of bases. in case of single inheritance base , derived object aligned in memory, value of pointer derived type, have same address same pointer converted pointer base type. in case of multiple inheritance (assuming bases not empty), not case. first base[*] can aligned full object.

the implication of lack of alignment this pointer need adjusted point appropriate location, depending on final overrider of virtual function in complete object. naïve implementation store both offset , pointer function in vtable, use offset adjust pointer, jump function. imply addition (of possibly 0) this pointer every call virtual function. in real life, compilers store single pointer function refer either final overrider if this pointer not need adjusted or small trampoline function offset this pointer , forward overrider.

you explicitly mentioned not interested in virtual inheritance, , skip complex further explanations. of above bit of simplification, idea. height of inheritance chain not matter, width can have small impact (an jump , addition, or similar costs, depending on implementation.

if interested, recommend pick the c++ object model lippman. if book on 15 years old, , contains typos , forth, describes many of issues in implementing object model , comments on of solutions.

[*] empty base optimization, becomes of empty bases and first non-empty base.