Re-calling an object's constructor

What I am interested in is a way to recall and object's constructor after it is built; something like this:
1
2
3
  Enemy enemy(player);
  ...
  enemy(player);


I know that you can do this with a pointer:
 
  Enemy *enemy = new Enemy();

However, the rest of my code is already set up to use normal Enemy objects, so I don't want to change everything.
Why do you have a need for this? You have a design flaw in your code.

It is possible, but you need to destruct the object first.
1
2
enemy.~Enemy();
new (&enemy) Enemy(player);
Note that you should never need to do this. Please don't do this.
A proper in most cases way to recall an object constructor is to move-assign a temporary: enemy = Enemy(player);
Why? I just don't want a bunch of objects created... I only have one running at a time and when it calls a function, which I guess I should move to its destructor, another one is made.

Note:
It's an RPG-style code... so an Enemy is someone you fight and when it dies another one is made in it's place... or just call it's constructor. But I guess if it works, it is fine; I am not trying to be professional.
Create a function called reset (or something like that) and move everything from the constructor to this function. Call reset from the constructor, and other places where you want it to run.
Last edited on
Ameji72 wrote:
I just don't want a bunch of objects created...
Don't worry about this. Computers from ten years ago are far more powerful than you seem to think today's computers are.
one way to create another one once it dies it to understand how scope works. for example

1
2
3
4
5
6
7
8
9
10
11
12
13
bool game_over = false;
while (!game_over) {
    Enemy enemy();//1 enemy will be created until it dies then it will be deleted and then remade
    while (enemy.isAlive()) { //will exit this loop if the enemy is dead.
        //Enemy attack
        //Player attack
    }//Enemy is dead here
    //oh look we're at the end of the Enemy instance called "enemy"'s life span in this program
    //   it's about to be deleted. But if the bool game_over is not true, the program will create
    //   another enemy until it is.
    if (!continue_playing())
        game_over = true; 
}


shoot i always forget that continue is a keyword xD
Last edited on
If at time only one instance of class you need to create, then better you should make that class as singleton class.
akash16 wrote:
If at time only one instance of class you need to create, then better you should make that class as singleton class.
This is certainly not a valid use case for the singleton pattern. In my opinion the only valid use case for a singleton is ensuring that global resources are not duplicated in memory.
Topic archived. No new replies allowed.