Why are you allocating new states on the heap at runtime? A registration system would work much better and would pre-cache all the state handlers.
Simply put in its simplest form you want to do this:
Code:
if (conditional)
{
Foo();
}
So you need a state or a conditional and a method or method within an object to handle said state.
At setup time:
Code:
IStateHandler *pHandler = new SpecificStateHandler();
StateManager->RegisterForState(STATE_INTRO,pHandler);
..
...
StateHandler->SetState(STATE_INTRO);
while (running)
{
StateHandler->Update();
}
StateHandler will call the appropriate handler for the state.
Code:
class IStateHandler
{
public:
virtual ~IStateHandler() { }
virtual bool HandleState() = 0;
};
class SpecificStateHandler : public IStateHandler
{
public:
SpecificStateHandler() { }
virtual ~SpecificStateHandler() { }
virtual bool HandleState()
{
// Handle state here
}
};
Possible interface for IStateManager
Code:
class IStateManager
{
public:
virtual ~IStateManager() { }
virtual void Update() = 0;
virtual bool AddState(unsigned int stateID) = 0;
virtual bool RemoveState(unsigned int stateID) = 0;
virtual bool RegisterHandler(unsigned int stateID,IStateHandler *pHandler) = 0;
virtual bool UnregisterHandler(unsigned int stateID,IStateHandler *pHandler) = 0;
virtual bool SetState(unsigned int stateID) = 0;
};
The state manager does not require an enumeration and allows unique states to be added and removed. This state system could potentially allow for multiple handlers for states or it could only allow one handler per state. This is not a complete state machine in its current form as it has no transition handlers or events that transition from state to state. The boolean returns are there as an option for the method to notify of errors. For the sake of brevity I did not check for errors in my sample code.