nhnl nhnl - 22 days ago 14
Java Question

Instantiating derived types in C++

Imagine I have a Base class, and two classes that derive from it, One and Two. In Java, I could have the following scenario:

Base b;
if(condition)
b = new One();
else
b = new Two();


where the object type is determined at runtime (the above objects go on the heap).

In C++, I want to be able to instantiate the object type at runtime as well - where all I know is that they both share the same Base type - but I want to keep it stack allocated, like so:

Base b;


What's the best way to do this?

Answer

What's the best way to do this?

You can't. If you declare a variable type as Base, the stack allocation for it will be suitable for holding an instance of Base but not an instance of a derived type (which might be larger, though even if it is not, you still cannot do what you ask; the runtime type of a variable in C++ is always the same as its declared type). At best, you could slice the derived instance into a Base-type variable.

The best bet is to use a pointer, optionally wrapped in a shared_ptr or unique_ptr to give you similar semantics (i.e. to have the object be automatically destroyed when it goes out of scope, assuming ownership hasn't been transferred).

Base* b = (condition) ? (Base *) new One() : new Two();
auto bptr = shared_ptr<Base>(b);

Note that what this gives you is effectively the same as the Java. The object itself is heap allocated, but the reference to it is stack allocated. Despite the syntax, a reference-type Java variable is essentially equivalent to a pointer in C++.

Comments