Programming Language

In C++, what’s a vtable and how does it work?

So, what is a Vtable?
Before we answer that question, it’s important to remember that C++ is an object oriented program language that implements polymorphism and inheritance. Those are complicated enough to fully understand, but they are also the reason why Vtables exist.
So, let’s start out with an example. We are going to create a class called ‘vehicle’. For our case, a vehicle is any kind of mechanical device that can move a person from point A to point B. A vehicle can be a bike, a car, or even a blimp.

class Vehicle {
Integer numberOfTires
Integer maximumSpeed
Virtual Function setSpeed
}
The class we just created is a very broad stroke. It can describe all of our examples: a bike, a car, or a blimp. So let’s create the individual classes.
Class bike inherits Vehicle {
Function setSpeed
}
Class car inherits Vehicle {
Function setSpeed
}

Class blimp inherits Vehicle { }

So, I did something interesting there. Bike and Car have their own ‘set speed’ functions that overwrite the main Vehicle ‘set speed’ function while the blimp just goes ahead and uses it. Bike, Car, and Blimp don’t mention how many tires there are because they all inherit it from Vehicle.

This has been a nice review on inheritance and polymorphism, hasn’t it? But how does a Vtable fit into all of this? Well, remember when the code is compiled, the compiler reads the code in a certain direction. It doesn’t jump around. If the compiler approaches a function, like setSpeed, and doesn’t know where to go with it or what to do it might cause an error. We don’t want it to freak out though. So, the compiler references a Vtable.

Each class – vehicle, bike, car, and blimp – can have their own Vtable. At compile time, the compiler is nice enough to stick a pointer inside each class to point to its Vtable so the compiler has directions for itself. The Vtable itself is nothing more than an array full of other pointers telling the compiler where to go. It acts like a tiny address book. This way, the compiler knows to check class Vehicle for setSpeed without getting lost.

There are a couple of important things to mention. Vtables only care about virtual functions. Note the demarcation of ‘virtual’ for setSpeed in the vehicle class. Also, programmers don’t create the Vtable. It is done automatically. Vtables are also not exclusive to C++ but are a common thing for all object oriented languages.

And there you have, that’s more or less what a Vtable is and how it is used.

Leave a Reply