0

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?

Horst Walter
  • 13,663
  • 32
  • 126
  • 228

1 Answers1

1

The functionality that differs between your classes should be exposed via virtual functions.

Then, you don't need to cast down the object and you can just return unit. The member functions called will be the correct ones for the objects you've created.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180