Search code examples
c++vtable

What is the structure of virtual tables in C++?



For Example I have two "intefaces" and class type:

class IPlugin
{
  public:
    virtual void Load(void) = 0;
    virtual void Free(void) = 0;
};

class IFoo
{
  public:
    virtual void Foo(void) = 0;
};


class Tester: public IPlugin, public IFoo
{
   public:
           Tester() {};
          ~Tester() {};

           virtual void Load()
           {
              // Some code here
           }

           virtual void Free()
           {
              // Some code here
           }

           virtual void Foo(void)
           {
              // Some code here
           }
 };

What structure vtab actually has for instance of type Tester? And how would be dynamic_cast operator act ( I mean how dynamic_cast operator would scan vtab for valid reference type convertion) in expression:

Tester* t = new Tester();
IPlugin* plg = dynamic_cast<IPlugin*>(t);
IFoo* f = dynamic_cast<IFoo*>(plg);  

Thanks in advance!


Solution

  • Virtual tables in C++ is an implementation detail. One possible implementation is shown on the diagram below.

    Virtual table diagram

    Two instances of the class (A and B) exists. Each instance has two vtbl pointers and the vtbl contains pointers to actual code.

    In your example there is no instance data, but I have for illustrative purposes assumed that each class contains some instance data.

    When a pointer to Tester is cast to a pointer to IFoo the pointer is adjusted as shown on the diagram. Instead of pointing to the start of the instance data it points to the IFoo part of the instance data.

    The neat thing is that a caller using an IFoo pointer doesn't have any knowledge about the data surrounding the IFoo part of the class. The same can be said of for a caller using an IPlugin pointer. This pointer happens to point to the start of the instance data also pointed to by a Tester pointer but only a caller using a Tester pointer knows the entire layout of the instance data.

    Using dynamic_cast requires RTTI (Run-Time Type Information) which is not on the diagram. The vtbl will contain additional type information that given a say IFoo pointer to an instance of Tester allows the code at run-time to discover the actual type of object pointed by the pointer and use that to downcast the pointer.