Virtual Functions & Virtual Tables.

We all know what virtual functions are and how to use them but it’s also important to know how they are implemented under the hood. Lets first take a look a non-virtual functions. They are easy because a particular function call always maps to a particular part of the code. The compiler can calculate the address of that function at compile and link time. At runtime all it does is make a call to a fixed address.

Virtual Functions are tricky because the code called depends not only on the specific functions call made, but also the type of object that the function is called on. This can be resolved using  Virtual Tables. The virtual tables also know as vtables are just a table of pointers to functions. An important thing to note about vtables us that it only contains pointers to virtual functions, non-virtual function addresses are still computed at compile time and are called directly to the code. It is also important to note that there is only one vtable per class not per object of the class. This is very important because if you have, lets say a class called Particle and you have 10000 objects of class Particle then they will all share the same vtable assuming that they are the same type and have at least one virtual function.

The size of an one object containing at least one virtual function increases by at least the size of a pointer, on most platform that is 4 bytes. Knowing the cost of virtual functions and being aware is important on platform when more limited memory.

Posted in C++

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s