I have this code :
A * a = new A;
a->fun();
delete a;
a = new B;
a->fun();
delete a;
What I need to do is to make it print :
A::fun() //being printed by A's fun()
B::fun() //being printed by B's fun()
without using the virtual keyword. Classes can be altered although the main code has to remain unchanged. How can this be done?
(Also, B is derived from A)
I hope this is for educational purposes.
If the destructor of
ais notvirtualthis results in undefined behavior. So the destructor must bevirtual.If the destructor is
virtual, you can usedynamic_cast. So, you can changeA::footo:Alternative with non-
virtualdestructor (undefined behavior if you calldelete):