I'm new to C++ and as a college proyect I'm building a 2D platformer with some classmates, I recently read that it's a good idea to have a stack of gamestates instead of a single global variable with the game state (which is what I have now) but I'm not sure how to do it.

Currently this is my implementation:

class GameState
        virtual ~GameState(){};
        virtual void handle_events() = 0;
        virtual void logic() = 0;
        virtual void render() = 0;

class Menu : public GameState
        void handle_events();
        void logic();
        void render();

Then I have a global variable of type GameState:

GameState *currentState = NULL;

And in my Main I define the currentState and call it's methods:

int main(){
    currentState = new Menu();

How can I implement a stack or something similar to go from that to something like this:

int main(){
    statesStack.push(new Menu());
  • 4
    \$\begingroup\$ the only place where I've found a need for a state stack is when making context sensitive help, or complex menu driven systems (at which point, question the usability of complex menu driven systems because they suck to use). In those cases and when using C++, I used std::stack<T>, because implementing your own stack is silly unless a) you are learning to implement a stack or b) your platform does not provide an adequate implementation for a stack. \$\endgroup\$ – PlayDeezGames Oct 8 '13 at 17:00
  • \$\begingroup\$ You seem to be asking for a lot of help lately, and have previously indicated it was part of your homework. If this is the case, you aren't going to learn a thing by asking people to tell you how to do it. \$\endgroup\$ – Evan Oct 8 '13 at 17:31
  • \$\begingroup\$ @Evan the next time I stumble upon this same problem I'll know how to do it... futhermore I cannot do it if I don't know how, the game has around 3000 lines, probably less than 20 from SE \$\endgroup\$ – Lisandro Vaccaro Oct 8 '13 at 17:55
  • \$\begingroup\$ If you feel you are on the right path, then stay the course. \$\endgroup\$ – Evan Oct 8 '13 at 18:28

Browse other questions tagged or ask your own question.