Say I have class B that derives from class A. If B overrides a virtual method f of class A, what exactly happens with this virtual method when I assign an instance of class B into an instance of class A?
Most basic example:
#include <stdio.h>
class A
{
public:
virtual void f()
{
printf("I am A\n");
}
};
class B : public A
{
public:
virtual void f()
{
printf("I am B\n");
}
};
int main()
{
// Instance of B:
B b;
b.f();
// Reference to A:
A& a_ref = b;
a_ref.f();
// Assignment:
A a = b;
a.f();
return 0;
}
Output:
[windel@hoefnix]$ g++ wtf.cpp
[windel@hoefnix]$ ./a.out
I am B
I am B
I am A
When using a reference, all is going as expected, but with a cast, I was put on the wrong foot here.