I'm having hard time to understand why the code below print C::f2 instead of B::f2.
When a non-virtual function is called the implementation must use the static type of the object on which the function is being called to determine the correct function to call. A function stored in a vtable accessed by a vptr will be dependent on the dynamic type of the object, not any static type of a reference or pointer through which it is being accessed.
I'm a bit lost, Inside A::f1 there is a call to f2. How does the compiler know which method to call?
My assemption:
- The compiler somehow remmber that we are inside object of type C.
- The compiler check if C contain a non virtual method name f2. a. if yes, run it. b. use the object's pointer to access his vtbl and run the right f2.
Am I right?
struct A
{
void f1()
{
f2();
}
virtual void f2()
{
cout<<"A::f2"<<endl;
}
};
struct B:public A
{
virtual void f2()
{
cout<<"B::f2"<<endl;
}
};
struct C:public B
{
void f2()
{
cout<<"C::f2"<<endl;
}
};
int main()
{
C c1;
c1.f1();
return 0;
}