#include <iostream>
usingnamespace std;
class X {
public:
void f()
{
cout << "1" << endl;
}
};
class Y : public X
{
void f() {
cout << "2" << endl;
}
};
int main() {
X x;
Y y;
X* p = &x;
p->f();
p = &y;
p->f();
return 0;
}
The code you've posted will print "11". Did you copy it correctly? Shouldn't line 14 print "2"?
X::f() is not virtual, so since p is a X *, p->f() will always make a static call to X::f(), regardless of the run-time type of *p. For the call to be dynamic, X::f() needs to be virtual.