A vtable is the common name for a special data structure used by some C++ compilers. The vtable, short for "virtual table", is used to dynamically bind virtual functions to objects at runtime. The vtable is not intended to be used directly by the program, and as such there is no standardized way to access it.

A vtable typically stores pointers to all of the virtual functions within a class. It is used at runtime by the C++ program to dynamically bind the proper methods to an object. Each object of a class with virtual functions transparently stores a pointer to its vtable. A call to a virtual function is resolved by following this hidden vtable pointer and from there it gets the address of the virtual function. Virtual base classes are handled in a similar same way; one implementation uses an additional level of indirection for the base class.

The C++ notation for a pure virtual function, "= 0", is directly linked to its original representation in the vtable as a null pointer in the original cfront C++ translator.

This allows the proper function to be called, even if the object is being referenced through a base class. This is a key requirement for the OO concept of polymorphism, where a specialized object can be treated as a more generic object, yet retain its specialized behavior.

The vtable is the simplest and most straightforward implementation of the virtual function calling mechanism; it was Bjarne Stroustrup's original implementation of this mechanism for C++. Essentially an array of pointers to implementations of member functions (and offsets to descendant pieces of virtual base classes), each instance of a class with at least one virtual member function carries a vtable around as a secret data member.

Although the C++ standard does not explicitly specify that the virtual function calling mechanism has to be implemented by a vtable, nearly all C++ compilers (especially g++) implement it this way. The development of an alternative mechanism is probably very expensive, and so any compiler vendor that may have developed one will be motivated to keep it a trade secret.

One possible alternative implementation still involves a vtable, but *outside* the class, as part of a pointer or reference to an instance of the class. This means that pointers to classes will be larger than pointers to most POD types, but something like that is already necessary for char * on some platforms.

Log in or register to write something here or to contact authors.