Sven van den Boogaart
Sven van den Boogaart

Reputation: 12317

c++ initialize non pointer object again

In my header file I have:

class Game
{
private:
    string _name;
    Level _currentLevel;
public:
    Game();
    ~Game();
    void setName();
    void run();
};

In my cpp file I have my run function:

void Game::run()
{

    bool finished = false;
    string input;
    while (!finished)
    {
        // get input
        std::cout << "Enter a command: \n";
        std::getline(std::cin, input);
        if (input == "quit")
        {
            finished = true;
        }
        else if (input == "new")
        {
            Level _currentLevel;
        }
        else if (input == "print")
        {
            _currentLevel.printMap();
        }
        else
        {
            std::cout << "Unknown command! \n";
        }


    }
}

constructor and printmap method of Level

Level::Level()
{
    _width = RandomGenerator::Instance()->getRandom(6, 10);
    _height = RandomGenerator::Instance()->getRandom(6, 10);
    for (int y = 0; y < _height; y++)
    {
        for (int x = 0; x < _width; x++)
        {
            addRoom(x, y);
        }
    }
}

void Level::printMap()
{
    for (int y = 0; y < _height; y++)
    {
        for (int x = 0; x < _width; x++)
        {
            if (x != 0)
                cout << " - ";
            cout  << _map[coordinate(x, y)].getSize();
        }
        cout << "\n";
    }
}

However when I type new, that runs Level _currentLevel; (to create a new non pointer object), the object dosnt change. I can see it dosn't change the values of level when I run printmap (which prints a map with 30 random values created in the Level constructor). While debugging the value of _height changes in the Level constructor. How should the value of _currentLevel be updated from my Game class?

Upvotes: 0

Views: 1474

Answers (2)

Donnie
Donnie

Reputation: 46913

Your new block creates a local stack variable that happens to have the same name as your instance variable (_currentLevel). It does not overwrite the instance variable, and that's why nothing changes.

You have a few straightforward choices:

  • Use a pointer. I suggest using a shared_ptr so you don't have to worry about deallocating memory on your own.

  • Extend Level to have an Initialize function. The constructor can call this, or you can call it from other code later if you want to re-initialize an existing variable.

  • Copy a new local variable to the instance variable.

Personally, I'd suggest the pointer, but either works.

Upvotes: 3

bgarcia
bgarcia

Reputation: 154

For starters the prototypes should be in the header and the implementation in the source file. Apart from that, in game::run you declare a second local _currentlevel which shadows the class variable. Outside the constructor, you never modify the class field.

Replace the shadowing line with this->_currentlevel = Level();

Upvotes: 0

Related Questions