Site Tools


wiki:cpp-vtable

Table of Contents

C++ Vtable

Vtable (virtual method table) is the compiler-generated table of function pointers used for virtual function dispatch. Each class with virtual functions has a vtable; each object holds a pointer (vptr) to its class's vtable. When a virtual function is called through a pointer or reference, the program looks up the function in the vtable.

Understand vtables to reason about performance and object layout; virtual function call overhead is typically one indirect pointer indirection.

Example

This example shows how virtual functions use vtables for dynamic dispatch.

// compile: g++ -o vtable vtable.cpp
// run: ./vtable
// description: vtable enables dynamic dispatch for virtual functions
 
#include <iostream>
 
class Animal {
public:
    virtual ~Animal() = default;
    virtual void speak() { std::cout << "Animal sound\n"; }
};
 
class Dog : public Animal {
public:
    void speak() override { std::cout << "Woof\n"; }
};
 
class Cat : public Animal {
public:
    void speak() override { std::cout << "Meow\n"; }
};
 
void animalSound(Animal* a) {
    a->speak();  // virtual call: looks up vtable
}
 
int main() {
    Dog dog;
    Cat cat;
    Animal* animals[] = {&dog, &cat};
 
    for (auto animal : animals) {
        animal->speak();  // vtable dispatch
    }
 
    return 0;
}
wiki/cpp-vtable.md · Last modified: by 127.0.0.1