Consider this small program:
#include <iostream>
struct Base {
virtual void say_hello() {
std::cout << "Hello from Base" << std::endl;
}
};
struct Derived : public Base {
void say_hello() override {
std::cout << "Hello from Derived" << std::endl;
}
};
int main(void) {
Derived d;
d.Base::say_hello(); // prints "Hello from Base"
(d.*(&Base::say_hello))(); // prints "Hello from Derived"
return 0;
}
When compiled and executed, it prints:
Hello from Base
Hello from Derived
As far as I understand, objects of both the Base
and Derived
classes are polymorphic objects and somehow contain runtime type information. That way the right overridden function can be choosen even if for base class pointers pointing to a derived object. I also learned that the overridden function from the baseclass is still available and can be called with an explicit call like:
object.Base::function()
In the small program above we can see, that this indeed works as expected. The say_hello
method from the base class is selected in the d.Base::say_hello()
expression and prints "Hello from Base"
.
What puzzles me now:
- Why does the second case not call the base class method?
- Is there a way to call the base member function through a member function pointer?
- And is there even a difference between the following two expressions?
&Base::function &Derived::function