I’m learning about polymorphism, and I am confused by this situation:
Let’s say I have the following C++ classes:
class A{
...
virtual void Foo(){
Boo();
}
virtual void Boo(){...}
}
class B : public A{
...
void Foo(){
A::Foo();
}
void Boo(){...}
}
I create an instance of B and call its Foo() function. When that function calls A::Foo(), will the Boo() method used be that of class A or B? Thanks!
Unless you qualify a function call with the class, all method calls will be treated equal, that is dynamic dispatch if virtual, static dispatch if not virtual. When you fully qualify with the class name the method you are calling you are effectively disabling the dynamic dispatch mechanism and introducing a direct method call.
The implicit
thispointer is not an important part of the discussion here, as exactly the same happens when the call is made with an explicit object:Note 1: in this example, the compiler can elide the dynamic dispatch mechanism as it knows the concrete type of the instance (it sees the definition and it is not a reference/pointer) but you can imagine the same would happen if
bwas a reference, or equivalently if it was a pointer with->instead of.