Suppose, that I have an abstract base State
class and at least two derived classes AnimalState
and PlantState
(also abstract). Also, I have many derived classes from AnimalState
and PlantState
.
class State{} // abstract
class AnimalState: public State{} // abstract
class PlantState: public State{} // abstract
//maybe few more of such classes here
class AnimalStateSpecific1: public AnimalState{}
class AnimalStateSpecific2: public AnimalState{}
... //many of them
class PlantStateSpecific1: public PlantState{}
class PlantStateSpecific2: public PlantState{}
... //many of them
Now suppose, that I use them in some kind of method that operates on base State
pointers. Those pointers are replaced over time with other pointers to different class from the State
hierarchy. It happens by some rule, specifically within the predefined state graph.
Now to the question part. In order to determine the next state, I need to know the previous one. But since I have only base State
pointers, I can not efficiently tell what type of state I have, without doing dynamic_cast
to every derived class in the hierarchy that is not good. I can have some enum
with all kinds of states that I have, but I do not really like that because I do not want to mix information from two hierarchy branches, as it is really different. Also, I do not like different enums
for every branch in the hierarchy such as AnimalStateEnum
, PlantStateEnum
etc.
What is the best solution for this problem? Maybe my design is not good from the start? I want to keep it as generic as possible and work only with base class objects, if possible.