Lets say I’ve got something like the following:
class A { virtual void g() = 0 }
class B : public A { virtual void g() { ... } }
class C : public A { virtual void g() { ... } }
... f(bool x)
{
if (x) { return B(); } else { return C(); }
}
bool get_boolean();
int main()
{
bool b = get_boolean();
... x = f(b);
x.g();
}
Is there anyway to do something like the above without calls to new, i.e. solely on the stack?
In function
fobjectsB()orC()are both temporary, so you can only return them fromfby value.Maybe boost::variant is for you. Then you don’t even need to have the method virtual or derive from a common base class.