I have the following code:
#include <iostream>
using namespace std;
class Parent {
public:
virtual void f() { cout << "Parent" << endl; }
};
class Child : public Parent {
public:
void f() { cout << "Child" << endl; }
};
void t1(Parent * p) { p->f(); }
void t2(Parent & p) { p.f(); }
int main() {
Child a;
t1(&a);
t2(a);
return 0;
}
I tested this both in Visual Studio 2013 and ideone.com, and both got the result:
Child
Child
I can understand t1
calling Child::f()
as the result of dynamic binding, but the second one has me puzzled - I expected the Parent &
to "fix" the type, so t2
would call Parent::f()
. Am I misunderstanding the rules? How does one explain this behavior?