Virtual table
- C++ course
- Intermediate
- Lesson 37/116
- 5 min
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.
Practice 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();.
Starter code
#include <iostream>
// Define Shape, Circle and Square classes here
int main() {
// Create two Shape* and print their areas
return 0;
}Sample 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;
}Expected output
314 100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its meaning
| Term | Meaning |
|---|---|
vtable |
Virtual table |
virtual |
vtable entry |
Shape* |
Dynamic binding |
override |
Override |
2 When is the vtable created?
class Shape { public: virtual int area(); };- At runtime
- In the destructor
- At compile time Correct answer
- Only while debugging
Explanation: The vtable is built at compile time for classes with virtual methods.
3 Complete the pointer assignment
Shape* s = new ____();
Shape* s = new Circle();
Explanation: A derived instance is assigned to a base pointer.