title: Casting from abstract base class pointer to derived class
body: <p>I'm trying to create a state manager for my game, and I have 4 classes: </p>
  
  <p>GameState:</p>
  
  <pre><code>  // foward declaration to avoid circular-referency
    class StateManager;
  
    class GameState
    {
      public:
        virtual ~GameState() { }    
        virtual void update(StateManager* gameManager) = 0;
        virtual void draw(StateManager* gameManager) = 0;
  
     protected:
        GameState() { }
    };
  </code></pre>
  
  <p>StateManager:</p>
  
  <pre><code>  class StateManager
    {
      public:
        StateManager();
        virtual ~StateManager();
  
        void addState(GameState* gameState);
        void update(StateManager* stateManager);
        void draw(StateManager* stateManager);
  
      protected:
        // store states in a unique_ptr to avoid memory leak
        std::vector&lt;std::unique_ptr&lt;GameState&gt; &gt; states_;
    };
  </code></pre>
  
  <p>Game:</p>
  
  <pre><code>class Game : public StateManager
  {
  public:
    void compute()
    {
      // call methos of statemanager
      update(this);
      draw(this);
    }
  }
  </code></pre>
  
  <p>And MainMenu:</p>
  
  <pre><code>class MainMenu : public GameState
  {
    public:
      // override the pure virtual methos of GameState
      void update(StateManager* stateManager)
      {
        // problem here.
        // I need to handle instance of Game in this class, 
        // but the pointer is one StateManager
      }
      void draw(StateManager* stateManager) {}
  }
  </code></pre>
  
  <p>When I initialize my game like so: <code>game.addState(new MainMenu())</code>.</p>
  
  <p>The only way I can access the class <code>Game</code> in <code>MainMenu</code> is by casting the pointer?</p>
  
  <pre><code>// MainMenu class
  void update(StateManager* stateManager)
  {
      Game* game = (Game*) stateManager;
      game.input.getKey(ANY_KEY);
      //...
  }
  </code></pre>
  
  <p>Is this right? Something tells me I'm doing it wrong.</p>