Imagine I have a Base class, and two classes that derive from it, One and Two. In Java, I could have the following scenario:
b = new One();
b = new Two();
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
The best bet is to use a pointer, optionally wrapped in a
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++.