I have two class hierarchies:
BaseUnit <- S1Unit , BaseUnit <- S2Unit, ..S3Unit, S4Unit
and
Base <- S1 , Base <- S2
In Base
I stored the unit's value.
class Base {
protected: BaseUnit unit; // actually this is an upcast of S1Unit, S2Unit
// of course I do several things with unit on methods of Base
}
which is based on S1Unit, S2Unit ..
S1::S1(S1Unit s1unit) : unit(s1unit) { .. }
However, if I now would like to return the specialized unit in S1, how would I best do this?
S1Unit S1::getUnit() const { return this->unit; /* how to cast down? */ }
I could implement S1Unit
a constructor of BaseUnit
S1Unit::S1Unit(BaseUnit)
which works fine, but this kind of downcast copy constructor somehow is not very nice. All answers I have checked show examples using pointers.
What would be a better solution? Any alternatives?