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?
There is no way to implement virtual functions in plain C, because C has no notion of inheritance. Update: As is discussed in the comments below, it is possible to do something similar to virtual functions in straight C using structures and function pointers.
To implement virtual functions, C++ uses a special form of late binding known as the virtual table. The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.
No. A vtable only contains pointers to virtual functions in the same class or file.
For every class that contains virtual functions, the compiler constructs a virtual table, a.k.a vtable. The vtable contains an entry for each virtual function accessible by the class and stores a pointer to its definition. Only the most specific function definition callable by the class is stored in the vtable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With