I am trying to understand the sense of virtual fuctions and so I wrote the following piece of code:
Code:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void doit() { cout << "Base" << endl; }
};
class Derived : public Base
{
public:
virtual void doit() { cout << "Derived" << endl; }
};
int main()
{
Base b;
Derived d;
Base &reference = b;
reference.doit();
reference = d;
reference.doit();
}
When I compile it, I get:
Why? Shouldn't the second call return "Derived"?
Conversely, when I write:
Code:
int main()
{
Base b;
Derived d;
Base &reference = d;
reference.doit();
reference = b;
reference.doit();
}
It returns:
What is the point of the virtual functions if by re-assigning the reference to a different type, it still uses the old function?