Question about class inheritance

I have a base class that represent my game's scenes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Base Class
class GameScene {
public:
    GameScene(const std::string& name = "Unknown Game Scene");
    virtual ~GameScene() = default;

    virtual void Load() {}
    virtual void Unload() {}

protected:
    std::string name;
};

//----------------------------------------
// Some Scene
class Menu : public GameScene {
public:
    Menu();
    virtual ~Menu() = default;

    virtual void Load() override;
    virtual void Unload() override;

private:
};


In my main file I'd like to store the "currentScene" and call functions on that scene like so:

1
2
3
4
5
6
7
8
9
10
int main () {

    GameScene currentScene;
    Menu menu;

    currentScene = menu;

    currentScene.Load();

}


But when I call .Load on currentScene it always calls the base class Load function, not the current one which is Menu. I'd have to directly call menu.Load() for it to work.

How can I get currentScene to call the actual current scene which in this case is Menu, instead of the base class? I want to be able to switch currentScene to different scenes.

Hope I made sense, thanks!
The only way to use dynamic polymorphism is through either pointers or references. In your case, where you need to repoint the name to different objects, you need pointers:

1
2
3
4
5
6
std::unique_ptr<GameScene> currentScene;
currentScene = std::make_unique<Menu>();
currentScene->Load();
currentScene->Unload();
currentScene = std::make_unique<FooScene>();
currentScene->Load();
Ohhh got it, got it. Now I know. Thanks Helios, worked perfectly!
Topic archived. No new replies allowed.