Vtables…a quick look

I’m sure it’s all a term we’ve heard in our C++ lives right? But what are vtables? What do they give us in C++?

Well, they’re kind of a big deal actually.

First of all, as you’ve probably guessed, it stands for Virtual Table.  But secondly, and perhaps more importantly, without vtables, we wouldn’t have runtime-polymorphism available to us in C++, as all the references to the functions would be bound at compile time.

So what is a Vtable?

Well, it’s a table of function pointers.  Each object that has a virtual function, has a vtable pointer, which points to the virtual table for objects of its type.

Let’s have a look at some code.


struct baseStruct
    virtual void createWidgets() {}

struct derivedStruct: public baseStruct
    virtual void createWidgets() {}

void makeWidgets(baseStruct * widget)

int main()
    derivedStruct d;

The widget pointer in makeWidgets is pointing to a baseStruct object. At run time, the code should call derivedStruct::createWidgets since baseStruct::createWidgets() is virtual.

It only needs to look up the entry for baseStruct::createWidgets() in the virtual table, and then calls teh function the entry in the vtable is pointing too.

At compilation time, the compiler can’t know which code is to be executed by widget->createWidgets() call since it’s not known at compile time what widget points too.

I’m still learning myself, but this is very much a quick overview of what a vtable is.

Happy coding


About welshboy2008

In my spare time, I read, listen to music, play my guitar among other stuff. I love to write computer programs too. In various languages. But mostly C# and Java. I'm currently learning: PHP, Javascript, XML, ASP.NET, Python, C and Assembler.

Posted on 24/09/2018, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: