Let say we have below program:
class A
{ public:
virtual fun(){};
};
class B:public A
{ public:
virtual fun(){};
};
int main()
{
A a1;
B b1;
}
My question is how many vtables
and how many vptrs
will be created, when we run this program?
Basically, 2. One for class A , one for class B (vftables) and 2 vfptrs, one for a1 and one for b1 . However, this is not standard mandated, so you could as well have none. (usually implementations use vftables, but its not mandated.
If you mean pointers to the virtual function table, it's important to understand: you need one pointer per class (without multiple inheritance I'll mention below), but you have to have a copy of such pointer everywhere the instance has to use the virtual table, which is needed to call virtual functions, to dispatch the ...
In a typical vtable-based implementation of virtual polymorphism, there will be: one vtable per class, containing the virtual function pointers and other metadata for that class; one vptr per object, pointing to the vtable for that object's dynamic class type.
Virtual table - A table created at compile time for every single class containing the most derived versions of virtual functions only. Virtual pointer - A data member silently inserted by compiler into the class specification and initialized to virtual table from within constructor.
Its heavily implementation dependent, but generally you'll get one vtable object per class that has any virtual functions (classes with no virtual functions or bases don't need them), and one vptr per object of a class with a vtable (pointing at the class's vtable).
Things get more complex if you have multiple inheritance and virtual base classes -- which can be implemented many ways. Some implementations use an addition vtable per additional base class (so you end up with a vtable per base class per class), while others use a single vtable with extra info in it. This may result in needing multiple vptrs per object.
The virtual
keyword in B is irrelevant -- if the function is virtual in the base class, it will be virtual in the derived classes regardless.
Note that this is strictly implementation dependent.
C++ Standard does not talk of vptr
or vtable
, the virtual mechanism is left out as an implementation detail for compilers. So practically, compilers can implement it without using vptr
or vtable
.However, almost all known compilers implement it using vptr
and vtable
.
Given the above, to answer your question:
Each class will have its own virtual table.
While each object has its own virtual pointer.
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