Possible Duplicate:
A question about virtual mechanism in C++
Is using vtable the only way to implement virtual member functions mechanism in C++? What other ways exist?
Possible Duplicate:
A question about virtual mechanism in C++
Is using vtable the only way to implement virtual member functions mechanism in C++? What other ways exist?
Another known mechanism is type dispatch functions. Effectively, you replace the vtable pointer by a typeid (small enum). The (dyanmic) linker collects all overrides of a given virtual function, and wraps them in one big switch statement on the typeid field.
The theoretical justifcation is that this replaces an indirect jump (non-predicatble) by lots of predicatable jumps. With some smarts in choosing enum values, the switch statement can be fairly effective too (i.e. better than lineair)
Technically, all that's required for dynamic dispatch is the ability to identify the dynamic type of an object, given a pointer to it. Thus, any sort of hidden (or not-so-hidden) typeid field would work.
Dynamic dispatch would use that typeid to find the associated functions. That association could be a hastable or an array where typeid is the index, or any other suitable relationship. vptr just happens to be the way to achieve this in the least number of steps.
Another possible implementation would be to store the pointers to virtual functions directly into the objects. Of course, this solution is never used in practice (at least in no languages I'm aware of) since it would lead to a dramatic increase of the memory footprint. However, it is interesting to note that a code using this implementation could actually run faster since it removes an indirection layer by suppressing the need for the vptr.
I'm not aware of any compiler which implements virtual functions without using vtable approach.
Theoretically, however, one could create an internal map of object pointers and a table of pointers to virtual functions, something like map<objPtr, functionTable*>
, to implement dynamic polymorphism through virtual functions. But then it would make the dynamic dispatching slower than vtable-approach.
It seems vtable-approach is probably the fastest mechanism to implement dynamic polymorphism. Maybe, that is why all compilers employ this approach!