Restarting the game and restoring objects

Introduction

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

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

My goal

In this method, I would like to restore an object of the Player class, so all variables will be reset.

My code is:

 Player player; //New game method Game::New() { player = new Player(); } //Game loop Game::Loop() { if(keyispressed(key)) { Game.New(); } } 

Any suggestions?

+4
source share
1 answer

You are misleading pointers and variables without pointers. new Player() returns the address of the dynamically allocated Player object. You cannot assign this address to a non-pointer Player variable; you need to declare Player as a pointer:

 Player* player = new Player(); 

You also need to remember the freed memory with the corresponding 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 will need to update any other code that you wrote that uses the player to use the member -> access operator . For example, player.name() will become player->name()

+4
source

Source: https://habr.com/ru/post/1346740/


All Articles