How can I create a polymorphic object on the stack?

c++, polymorphism, stack

Solution

You can't structure a single function to work like that, since automatic or temporary objects created inside a conditional block can't have their lifetimes extended into the containing block.

I'd suggest refactoring the polymorphic behaviour into a separate function:

void do_something(A&&);

switch (some_var)
{
case 1:
    do_something(A());
    break;
case 2:
    do_something(B()); // B is derived from A
    break;
default:
    do_something(C()); // C is derived from A
    break;
}

Problem

How do I allocate a polymorphic object on the stack? I'm trying to do something similar to (trying to avoid heap allocation with new)?: ``` A* a = NULL; switch (some_var) { case 1: a = A(); break; case 2: a = B(); // B is derived from A break; default: a = C(); // C is derived from A break; } ```

Original source

Related problems