4

Introduction

I am creating a small game in C++ and would like to create a function to restart the game.

First I am creating the object player. Then I have an if statement to determine when a certain key is pressed to call the New() method.

My goal

In that method I would like to reinstantiate an object of the Player class, so all variables will be resetted.

My code:

Player player;

//New game method
Game::New()
{
    player = new Player();
}

//Game loop
Game::Loop()
{
    if(keyispressed(key))
    {
        Game.New();
    }
}

Any suggestions?

user229044
  • 232,980
  • 40
  • 330
  • 338
Datoxalas
  • 1,261
  • 5
  • 14
  • 23

1 Answers1

5

You're confusing pointer and non-pointer variables. new Player() returns the address of a dynamically allocated Player object. You cannot assign this address to the non-pointer variable player; you'd need to declare player as a pointer:

Player* player = new Player();

You also need to remember to release the memory previously allocated with a matching delete:

// player starts out pointing to nothing
Player* player = 0;

//New game method
Game::New()
{
    // If player already points to something, release that memory
    if (player)
        delete player;

    player = new Player();
}

Now that player is a pointer you'll have to update any other code you've written which uses player, to use the -> member access operator. For example, player.name() will become player->name()

user229044
  • 232,980
  • 40
  • 330
  • 338