Context: I want to utilise state objects within my program to determine how the program functions during a state. I have an abstract class State
that each state derives from (to keep things simple lets say we have MenuState
and AboutState
), The current state is stored as type State.
I want to be able to create a new instance of AboutState
from within MenuState
and vice versa so that I can control which program state I am currently in and change state easily (This would return a State object since that is what my current states type is)
The problem I am getting is obviously that if I first create AboutState
, MenuState
does not exist yet (to the compiler) and crashes on compile. I thought to fix this by forward declaring MenuState
but I cannot cast MenuState
in the function because I have only forward declared it rather than creating a full class.
Essentially How do I forward declare / fix this circular reference issue, so that I can create each of the objects from the other?
I primarily use Java so excuse the obvious errors below but you get the point, I can't cast temp
-> IWorldState
even if I forward declare. (I think)
class AboutState : public IWorldState
{
public:
AboutState() {};
virtual IWorldState* handleInput(std::string input) {
MainMenuState temp;
*IWorldState state = (IWorldState)temp;
return state;
}
};
class MainMenuState : public IWorldState
{
public:
MainMenuState() {};
virtual IWorldState* handleInput(std::string input) {
AboutState temp;
*IWorldState state = (IWorldState)temp;
return state;
}
};
Also don't know know if It's ok to ask in the same question, but is there a more appropriate way to do this kinda functionality with objects or is there a different type of approach to moving between the different states? I considered the idea of creating all states at the start and passing the next state as a parameter to the constructor but i feel It's unnecessary if I can get this working.