0

This is a very similar problem to a question i have already looked at, answered here - Restarting a game and reinstantiate objects .

I want exactly the same thing except my problem is slightly different in that the object i wish to reinstantiate is 'global' and is only ever created when the program first runs.

At present i create the new 'Player' after my #includes and before my function prototypes ...

#include "Player.h"
#include "Monster.h"

using namespace std;

string MonsterTypes[3] = {"Orc","Goblin","Dark Rider"};
//create a stack of 'monsters'
stack<Monster>MonsterList;

Player* NewPlayer = new Player();

int NewGame();
void SetupPlayer();
void SetupMonsters();
void MainGame();
void Combat();
int GetMonstersLeft();

Do i need to create an entire factory class just to create a single player? Obviously when i call the function 'setupPlayer' i could create the player object in there, but would i not then have to pass 'NewPlayer' to every other function, i was just wandering if there was a way to avoid doing that?

Community
  • 1
  • 1
JabbaWook
  • 677
  • 1
  • 8
  • 25
  • 1
    One way to "restart" any program, is to simply create a new process that runs itself, while exiting the original process. It will seem like the program starts over completely from the beginning. – Some programmer dude Jan 31 '14 at 10:52
  • Just call `delete NewPlayer; NewPlayer = new Player();` – manuell Jan 31 '14 at 15:43

2 Answers2

1

You can create a new player in SetupPlayer, and assign it to NewPlayer.

Since your global NewPlayer is a pointer to a Player object, you can simply create a new Player in its place every time you call SetupPlayer(), as follows:

Player* NewPlayer = NULL;  // Initialized when calling SetupPlayer()

void SetupPlayer() {
    delete NewPlayer;  // Delete the previous player (if any)
    NewPlayer = new Player();
}
WaelJ
  • 2,942
  • 4
  • 22
  • 28
  • Please note that with the code above you the enter the dangerous and magic world of *undefined behavior*. Beware of the monsters. – Shoe Jan 31 '14 at 11:36
  • Because `delete`ing a `NULL` pointer is *undefined behavior*? – Shoe Jan 31 '14 at 14:50
  • That's not the case, it is defined as a no-op [by the standard](http://stackoverflow.com/questions/6172232/is-it-undefined-behaviour-to-delete-a-null-void-pointer) – WaelJ Jan 31 '14 at 17:10
1

You don't really need dynamic allocation. You can just declare an automatic variable like this:

Player player;

and then when you want to reset it you can use:

player = Player();

Always remember that dynamic allocation is expensive.


What I would probably do, instead, is to create a "factory" function:

Player make_player() {
    Player ret;
    // setup ret
    return ret;
}

So that you can get rid of that global object. Don't worry about the performance of copying the object back when returning: copies are elided by a well-known optimization (return value optimization - RVO).

Shoe
  • 74,840
  • 36
  • 166
  • 272