java - Instantiating derived types in C++ -
imagine have base class, , 2 classes derive it, 1 , two. in java, have following scenario:
base b; if(condition) b = new one(); else b = new two();
where object type determined @ runtime (the above objects go on heap).
in c++, want able instantiate object type @ runtime - know both share same base type - want keep stack allocated, so:
base b;
what's best way this?
what's best way this?
you can't. if declare variable type base
, stack allocation suitable holding instance of base
not instance of derived type (which might larger, though if not, still cannot ask; runtime type of variable in c++ same declared type). @ best, slice derived instance base
-type variable.
the best bet use pointer, optionally wrapped in shared_ptr
or unique_ptr
give similar semantics (i.e. have object automatically destroyed when 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 gives same java. object heap allocated, reference stack allocated. despite syntax, reference-type java variable equivalent pointer in c++.
Comments
Post a Comment