title: C++ State change not deleting old state?
body: <p>I'm working with Visual Studio and SDL to create a simple RPG game, however I noticed (when adding the music) that the music kept playing when I changed the gamestate, even though I stoped it in the destructor. If I stop the music right before changing the state though, the music stops (which made me realize that everytime i change the game state, the old state still remains, which I assume is using up a lot of memory (if i make the game big and change the state a lot).</p>
  
  <p>My state classes are set up like this:</p>
  
  <pre><code>// Gamestate.h
  #pragma once
  // includes here
  
  class GameState
  {
  public:
    virtual ~GameState() {}
    virtual void Update() {}
    virtual void HandleEvents() {}
    virtual void Logic() {}
    virtual void Draw(Graphics&amp; gfx) {} // Graphics is my own class
  
    GameState* getCurrentState()
    {
      return currentState;
    }
  
  protected:
    SDL_Renderer* renderer;
    GameState* currentState;
    Timer timer; // my own timer class
  };
  
  // GameStates.h; different than GameState.h
  #pragma once
  // includes here
  
  class IntroGameState : public GameState
  {
  public:
    IntroGameState(SDL_Renderer* renderer, KeyboardClient&amp; kbd);
    ~IntroGameState();
    void HandleEvents();
    void Logic();
    void Draw(Graphics&amp; gfx);
  
  private:
    Mix_Music* theme;
    // other variables defined here
  };
  
  // GameStates.cpp
  IntroGameState::IntoroGameState(SDL_Renderer* renderer, KeyboardClient&amp; kbd)
  {
    GameState::renderer = renderer;
    currentState = this;
    timer.Start();
  
    theme = Mix_LoadMUS("theme.wav");
    Mis_PlayMusic(theme, 0);
  }
  IntroGameState::~IntroGameState()
  {
    // This line does nothing (destructor not being called?)
    Mix_HaltMusic();
  
    delete theme;
    theme = NULL;
  };
  void IntroGameState::Logic()
  {
    if (timer.ElapsedTime() &gt;= 5) // if 5 seconds pass
    {
      // This line works
      Mix_HaltMusic();
      // I tried:
      // delete this;
      // delete currentState;
      // currentState = NULL; realized this was pointless when I just initialize it next
  
      currentState = new MovieSceneState(renderer, kbd);
  }
  
  // Game.cpp (where i actually change the state
  Game::Game()
  {
    // currentState here is defined within game.h
    currentState = new IntroGameState(renderer, kbd);
  }
  void Game::ComposeFrame()
  {
    currentState-&gt;HandleEvents();
    ChangeState();
    currentState-&gt;Logic();
    currentState-&gt;Draw(gfx);
  }
  void ChangeState()
  {
    GameState* s = currentState-&gt;GetCurrentState();
    currentState = s;
  }
  </code></pre>