In the following, how can I make it such that the program uses the draw method from MainMenuScreen instead of the one from GameScreen?
class GameScreen {
public:
virtual void GameScreen::draw() {
cout << "Drawing the wrong one..." << endl;
}
};
class MainMenuScreen : public GameScreen {
public:
void MainMenuScreen::draw() {
cout << "Drawing the right one..." << endl;
}
};
class ScreenManager {
public:
list<GameScreen> screens;
// assume a MainMenuScreen gets added to the list
void ScreenManager::draw()
{
for ( list<GameScreen>::iterator screen = screens.begin();
screen != screens.end(); screen++ )
{
screen->draw(); /* here it uses the draw method from GameScreen,
but I want it to use the draw method from
MainMenuScreen */
}
}
};
PS: I do not want to make GameScreen::draw purely virtual, so please suggest something else.
You can’t, unless you call it on a pointer or reference whose actual type is
MainMenuScreen.declares a
listof objects, not pointers or references. If you addMainMenuScreenobjects to it, they will lose type information because of object slicing and polymorphism will not work. You need:or, better yet: