Answer
A vtable is created when a class declaration contains a virtual function. A virtual table is introduced when the parent object โ anywhere in the hierarchy โ has a virtual function, allows you to call that parent Y. Any parent Y will not have a vtable (unless they have virtual for any other function in their hierarchical hierarchy )
Read on for discussion and tests.
- explanation -
When you specify a member function as virtual, there is a chance that you might try to use subclasses with the base class polymorphically at runtime. To support the C ++ language design performance guarantee, they proposed the easiest implementation strategy possible, that is, one level of indirection, and only when the class can be used polymorphically at runtime, and the programmer determines this by setting at least one virtual function.
You do not incur expenses on vtable if you avoid the virtual keyword.
- change: reflect your editing -
Only if the base class contains a virtual function, any other subclasses contain vtable. Parents of the specified base class do not have vtable.
In your example, all three classes will have vtable, because you can try using all three classes with A*.
- test - GCC 4+ -
#include <iostream> class test_base { public: void x(){std::cout << "test_base" << "\n"; }; }; class test_sub : public test_base { public: virtual void x(){std::cout << "test_sub" << "\n"; } ; }; class test_subby : public test_sub { public: void x() { std::cout << "test_subby" << "\n"; } }; int main() { test_sub sub; test_base base; test_subby subby; test_sub * psub; test_base *pbase; test_subby * psubby; pbase = ⊂ pbase->x(); psub = &subby; psub->x(); return 0; }
Exit
test_base test_subby
test_base does not have a virtual table, so any click on it will use x() from test_base . test_sub , on the other hand, changes the character of x() , and its pointer will be indirect via vtable, and this will be shown by test_subby x() .
So vtable is only used in the hierarchy when the virtual keyword is used. Older ancestors do not have a vtable, and if a downgrade occurs, it will be associated with the functions of the ancestors.
Hassan Syed Dec 26 '09 at 18:11 2009-12-26 18:11
source share