I thought for a long time that to use virtual functions, the class object has to be allocated with a pointer but I ran a test example and it seems it will perfectly work for objects on stack, it only depends on the syntax how you call it. But what I am doing feels almost like I am creating a 'cheat'to making the system do what I want, that is use a plain base class pointer to call a derived class virtual method.
#include <iostream>
using namespace std;
class B{
public:
virtual void call() { cout<<"B\n"; };
};
class D: public B{
public:
void call() { cout<<"D\n"; }
};
int _tmain(int argc, _TCHAR* argv[])
{
B b;
D d;
b.call(); // output is "B"
d.call(); // output is "D"
B* obj = &d;
obj->call(); // output is "D"
return 0;
}
Is this acceptable to do in release software or will it raise eyebrows? I can use this to great advantage in my software but I haven't seen anything like this before.
In my actual project, I have base and derived classes which are allocated on stack, lets call them Base
, DerivedA
and DerivedB
. I want to restructure and add virtual functions to the base and I thought I will have to allocate them on heap now but looks like I don't have to. Now my application could be in certain state where all operations will be done on DerivedA
or DerivedB
so I plan to add a pointer object:
Base * obj = &DerivedA;
Obviously when I need switch operations to other object, I just do obj = &DerivedB
and basically I will be using both objects indirectly through my new obj
pointer for all operations. Does this look sound?
Currently my code has if else
statements to do operation either on DerivedA
or DerivedB
and this will eliminate those.