Skip to content

Mechanics of virtual dispatch with vtables

Question

How do C++ compilers typically implement virtual function calls?

Short answer

With a virtual table per class and a hidden pointer per object. Each polymorphic class has a table of function pointers to its overrides, and each object stores a vptr to its class's table, set by the constructors. A virtual call loads the vptr, indexes the slot for that function and makes an indirect call, costing an extra pointer per object and an indirection per call.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.20, p.227; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question