Note that there are some explanatory texts on larger screens.

plurals
  1. POWeird polymorphism behavior with multiple inheritance in C++?
    text
    copied!<p>So, I'm writing on a little Pong game clone using SDL and I have the following setup.</p> <p>There's a general game class <code>SlimGame</code> which inherits from an FSM class and an event handler class:</p> <pre><code>// DEFINITION class SlimGame : public SlimFSM, public SlimEventHandler { protected: bool running; // indicates if the game is running public: bool isRunning() { return this-&gt;running; } void setRunning(bool r) { this-&gt;running = r; } void run(); // encapsulates the game loop }; // IMPLEMENTATION void SlimGame::run() { SDL_Event event; this-&gt;setRunning(true); while(this-&gt;isRunning()) { while(SDL_PollEvent(&amp;event)) { this-&gt;handleEvent(&amp;event); std::cout &lt;&lt; "MAIN LOOP Running: " &lt;&lt; this-&gt;isRunning(); &lt;&lt; endl; } // ... } } </code></pre> <p>The FSM class is irrelevant to the weird behavior, but the event handler class looks like this:</p> <pre><code>// DEFINITION class SlimEventHandler { public: SlimEventHandler() { } virtual ~SlimEventHandler() { } void handleEvent(SDL_Event *event); virtual void onExit(); }; // IMPLEMENTATION void SlimEventHandler::handleEvent(SDL_Event *event) { switch(event-&gt;type) { case SDL_QUIT: this-&gt;onExit(); break; } } void SlimEventHandler::onExit() { std::cout &lt;&lt; "PARENT onExit!" &lt;&lt; std::endl; } </code></pre> <p>And then I have my <code>PongGame</code> class itself which inherits from <code>SlimGame</code> (and therefore indirectly from <code>SlimFSM</code> and <code>SlimEventHandler</code>):</p> <pre><code>// DEFINITION class PongGame : public SlimGame { public: PongGame(); ~PongGame(); void onExit(); }; // IMPLEMENTATION void PongGame::onExit() { this-&gt;setRunning(false); std::cout &lt;&lt; "CHILD onExit!" &lt;&lt; std::endl; } </code></pre> <p>So with this setup I run my game like this and it starts up, nicely:</p> <pre><code>int main(int argc, char **argv) { PongGame game; // setup game.run(); // tear down return 0; } </code></pre> <p>However the event handling doesn't work the way it's supposed to work. If I click the window closing button the <code>SDL_QUIT</code> event get's fired and the method <code>handleEvent</code> gets called. This is fine, but the method itself calls <code>onExit</code> of its own, not the inherited method of the <code>PongGame</code> class, so I see:</p> <pre><code>PARENT onExit! </code></pre> <p>in the console instead of</p> <pre><code>CHILD onExit! </code></pre> <p>Shouldn't the derived method in <code>PongGame</code> be called, instead of the virtual empty implementation in <code>SlimEventHandler</code>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload