As I know, there's a virtual function table with a class type(contain virtual funcion). And there's pointer point to this talbe in a class.
My question is How does the function find the virtual function in this talbe, like:
1 2 3 4 5 6 7 8 9 10
class A
{
virtual fun1() {};
virtual fun2() {};
}
class B:public A
{
virual fun1() {};
}
the B virtual table like:
B::fun1()
A::fun2()
And when I declare B like A *a = new B;
there's a pointer
__vfptr
point to B talbe in a;
and when i call a->fun1() How the programme find fun1 from table?(I mean it find fun1 neither fun2) Is it decide by the compiler?
Internally the compiler assigns "indices" to each virtual function it finds.
When the compiler parses class A's declaration, it assigns fun1 index 0 and fun2 index 1.
When the compiler parses class B's declaration, there are no new virtual functions (just overridden ones),
so no new indices are allocated.
Therefore, when the compiler compiles a->fun1(), the compiler knows that the index of fun1 is 0, so it
looks in the 0th entry in the vtable.