I would like to use virtual functions of objects of different classes (derived from the same base class) without a) constructing all the objects or b) using new. Please see the code example:
#include <iostream>
class A{
public:
virtual void p(void){std::cout << "Im A" << std::endl;};
};
class B : public A{
public:
virtual void p(void) override {std::cout << "Im B" << std::endl;};
};
class C : public A{
public:
virtual void p(void) override {std::cout << "Im C" << std::endl;};
};
int main(){
bool cond = true; // some condition
A* o1;
if (cond) o1 = new B(); else o1 = new C();
o1->p(); // will call correct p(), i.e. either B::p or C::p but not A::p
A o2 = B();
o2.p(); // will call A::p
A* o3;
B tmp1; C tmp2; // construct both objects altough only one is needed
if (cond) o3 = &tmp1; else o3 = &tmp2;
o3->p(); // will call correct p(), i.e. either B::p or C::p but not A::p
A* o4;
if (cond) {B tmp; o4 = &tmp;} else {C tmp; o4 = &tmp;} // uses address of local variable
o4->p(); // will call correct p(), i.e. either B::p or C::p but not A::p
return 0;
}
I want the behavior of o1 but without calling new. o2 doesnt work (calls function of base class and if base class is abstract it doesnt work at all). o3 works but constructs all the different objects although only one is needed. o4 kinda "works" but uses a reference to a local variable outside of its scope.
What would be the correct / best / modern C++ way to do it?