How is the decision taken internally (during runtime) as to which function to call, either the base class or derived class function. In the below sample code how is decision taken to call fn() of B and fn2() of A.
Class A {
virtual void fn() { std::cout << "A" < <std::endl; }
virtual void fn2() { std::cout << "A-fn2" < <std::endl; }
};
Class B : A
{
void fn() { std::cout << "B" < <std::endl; }
}
int main() {
B b = new B;
A *a = &b;
a->fn();
a->fn2();
}
The output would be B and A-fn2()
Basically how is the decision taken at run time whether to call derived class function or base class function?
What you have is known as Dynamic/Run-time polymorphism.
The rule is:
The method to call at run-time is selected at run-time, depending on the actual object pointed to by the pointer.
How the compiler does this is completely implementation dependent. Typically, your code should only rely on the behaviors and not the internals of this. However, all known compilers implement this mechansim through a virtual table(
vtbl) & virtual pointer(vptr) mechanism.How is run-time polymorphism implemented?
Once a class has an
virtualmethod that class is known as a polymorphic class and the compiler creates avtblfor that class. Thevtblstores the addresses of all virtual methods in that class. The compiler also adds a special pointervptrto every object of that class. Thevptrpoints(stores the address of) to thevtbl.Once a class derives from such a polymorphic class, the compiler replaces the addresses of methods in the
vtblof the derived class with the address of overidding functions in the derived class.For non overidden methods the addresses are still that of the Base class methods.Thus, Each class has typically one
vtbl, while each object instance has avptr, which points to thevtbl. Thevtblof each class stores address of its own virtual methods.At run-time, the
vptrinside thethispointer is fetched and further the appropriate method address in thevtblis fetched & then it is called, this mechanism is called dynamic dispatch.Thus, due this mechanism the appropriate method to be called can be determined depending on type of the object which the pointer points to.
This C++-Faq is a good further read:
Inheritance — virtual functions