I thought that in C++ the implementation of B::f() is something like
that:
f(B *this) {
*(this->vptr[index])(this);
}
The value of index
is always known at compile time. The vtable is a "record" (a structure, like a C/C++ struct
) rather than an array or "table". So it's like:
void f(B *This) {
(This->vptr.ptr_f)(This);
}
Note: You don't need to dereference a pointer to function in either C or C++.
Is D::vf() called through the virtual mechanism in the following
example?
B *p = new D();
p->f();
It depends on the compiler and its "intelligence". At low optimization level, it will go through the virtual mechanism (aka dynamic dispatch).
With an efficient optimizer, the real type of the object used (here D
) can be determined, and dynamic dispatch can be avoided.