Tuesday, 8 July 2008

Virtuals, primer

Without fully understanding virtual tables, you can make some nasty gaffs. Without understanding the basics, you can get lost in some errors.

Firstly, the tables have to exist somewhere. They are real things, they are actually tables of function pointers. They have to go somewhere in memory, so most C++ compiler/linkers put them in the place where the first virtual function is defined for the most base class. In Geko we made the destructor/deconstructor that function. the simple Shutdown function was left inline.

Virtual tables are pointed to by the invisible first pointer in a class. You see it in the debugger, but not in the code. This pointer points to the array of function pointers that apply to it. Any function calls are made by finding the function's array reference (at compile time) and adding that to the vptr (at runtime) and calling that function instead of a statically bound one.

Multiple inheriters can have more than one vptr, which makes it even more complicated, and different compiler linkers handle it in different ways.

Other things to remember:
There is no reason to inline virtual functions. They can't be inlined, so inlining them just makes them look faster to humans. Virtual functions are slower than standard function calls, so use them for what they are good at and promote them to non virtual or inline whenever you see an opportunity.
You can write templated virtual code and you can write virtualised templates, but generally, you should get good at both before writing them together.
Post a Comment