C++
Virtual table
Learn the virtual method table (vtable) and runtime dispatch.
Virtual table
The virtual table (vtable) is a data structure the compiler builds for every class with virtual methods. Each object carries a hidden pointer to its class's vtable.
At runtime a->speak() looks up the correct implementation through the vtable. For example, with a Shape base class and Circle, Square derived classes, each object in a Shape* array uses its own vtable; ->area() returns the right value. The vtable provides polymorphism at a small cost.
vtable cost
The vtable adds a pointer to every object, causing a small memory increase. Each virtual method call is also one step slower because it is indirect.
This cost is negligible in most cases and worth the power of polymorphism. If performance is critical and polymorphism is not needed, you can avoid virtual. But if a class has a virtual destructor, the vtable already exists; making more methods virtual adds no extra cost.
Exercise Try vtable with a Shape hierarchy
Define a Shape class with virtual int area() returning 0. Circle and Square inherit from Shape; their area() override returns 314 and 100 respectively. In main create two Shape* and write std::cout << s1->area() << " " << s2->area();.
Show example solution
#include <iostream>
class Shape {
public:
virtual int area() { return 0; }
};
class Circle : public Shape {
public:
int area() override { return 314; }
};
class Square : public Shape {
public:
int area() override { return 100; }
};
int main() {
Shape* s1 = new Circle();
Shape* s2 = new Square();
std::cout << s1->area() << " " << s2->area();
return 0;
}
Test yourself
-
Match each piece to its meaning
- vtable
- Virtual table
- virtual
- vtable entry
- Shape*
- Dynamic binding
- override
- Override
-
When is the vtable created?
class Shape { public: virtual int area(); };
- At runtime
- In the destructor
- At compile time
- Only while debugging
Show answer
At compile time — The vtable is built at compile time for classes with virtual methods.
-
Complete the pointer assignment
Shape* s = new ____();
Show answer
Shape* s = new Circle();
Next lesson: Abstract classes