Original Post
I recently coded up a variation on a game state management policy in which a virtual class is created for game states and all states are derived from it. Here is the code: This is the main loop that uses it: I've inlcuded the one function which I think could cause trouble (changeState). Note that when it says "delete current_state" it is, in essence, deleting itself. It also followed by two executable lines. I have had not trouble so far, but I might have been lucky. Does the fact that the object delets itself while there are two remaining executable lines render this code prones to errors? When does the current_state object(the one carrying the changeState) actually get deleted?
class State{
public:
static State *current_state;
State(){}
virtual ~State(){}
virtual void init()=0; //Load resources
virtual void cleanup()=0; //Unload resources
virtual void pause()=0;
virtual void resume()=0;
void changeState(State *next_state )
{
current_state->cleanup();
delete current_state;
current_state = next_state;
current_state->init();
}
virtual void getInput()=0;
virtual void draw()=0;
virtual void update()=0;
};
extern State *current_state;
int main()
{
State::current_state = new Menu;
while(game_running)
{
State::current_state->getInput();
State::current_state->update();
State::current_state->draw();
}
printf("Game Finished\n");
return 0;
}