keywords: Virtual Functions, VTables
This is an array with pointers to functions, which are implementations of a particular virtual function. An index in this array represents particular index of a virtual function defined for a class. This includes pure virtual functions.
When a polymorphic class derives from another polymorphic class, we may have the following situations:
Not standard way - there’s no API to access them. Compilers may have some extensions or private APIs to access them, but that may be only an extension.
Only those that have at least one virtual function (be it even destructor) or derive at least one class that has its vtable (“is polymorphic”).
That’s a possible implementation, but rather not practiced. Instead there is usually a function that prints something like “pure virtual function called” and does abort(). The call to that may occur if you try to call the abstract method in the constructor or destructor.
The slowdown is only dependent on whether the call is resolved as direct call or as a virtual call. And nothing else matters. :)
If you call a virtual function through a pointer or reference to an object, then it will be always implemented as virtual call - because the compiler can never know what kind of object will be assigned to this pointer in runtime, and whether it is of a class in which this method is overridden or not. Only in two cases the compiler can resolve the call to a virtual function as a direct call:
Note though that virtual calls have only overhead of dereferencing two pointers. Using RTTI (although only available for polymorphic classes) is slower than calling virtual methods, should you find a case to implement the same thing two such ways. For example, defining virtual bool HasHoof() { return false; }
and then override only as bool Horse::HasHoof() { return true; }
would provide you with ability to call if (anim->HasHoof()) that will be faster than trying if(dynamic_cast<Horse*>(anim))
. This is because dynamic_cast
has to walk through the class hierarchy in some cases even recursively to see if there can be built the path from the actual pointer type and the desired class type. While the virtual call is always the same - dereferencing two pointers.
Origin:
https://stackoverflow.com/questions/99297/how-are-virtual-functions-and-vtable-implemented
It's enough for me to be sure that you and I exist at this moment. ― Gabriel García Márquez, One Hundred Years of Solitude
联系客服