vtable — table of function pointers for virtual functions. Enables runtime polymorphism.
1class Base {2public:3 virtual void foo() { std::cout << "Base\n"; }4 virtual void bar() { std::cout << "Base\n"; }5 int x;6};78class Derived : public Base {9public:10 void foo() override { std::cout << "Derived\n"; }11};1213// Memory layout:14// Base: [vptr | x]15// Derived: [vptr | x]1617// Virtual dispatch:18Base* p = new Derived();19p->foo(); // Follows vptr -> Derived vtable -> Derived::foo()2021// Cost:22// - Extra pointer per object (vptr).23// - Indirect function call.24// - Cannot be inlined.25// - Prevents some optimizations.
Optimization: