I have the following code:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void WhoAmI() const;
typedef void (Base::*WhoPtr)() const;
};
class Derived : public Base
{
public:
virtual void WhoAmI() const;
};
void Derived::WhoAmI() const
{
cout << "I am the derived" << endl;
}
void Base::WhoAmI() const
{
cout << "I am the base" << endl;
}
int main()
{
Base::WhoPtr func = &Base::WhoAmI;
Base theBase;
(theBase.*func)();
Derived theDerived;
(theDerived.*func)();
cin.get();
return 0;
}
Lets focus on the main:
int main()
{
Base::WhoPtr func = &Base::WhoAmI;
Base theBase;
(theBase.*func)();
Derived theDerived;
(theDerived.*func)();
cin.get();
return 0;
}
We have a local variable func
, who holds the address of Base::WhoAmI
.
Also, we have Base
and Derived
objects.
On line 2, we call the pointed func
from the base: (theBase.*func)()
.
I understand until now.
2 lines after, we call this from the derived: (theDerived.*func)()
.
It prints: I am the derived
. Why?
Both WhoAmI
are virtual
, that mean that the call dependent by the pointed object
, and not by the type.
the pointed object is func
who belongs to Base
. Why does it print I am the derived
instead of I am the base
?