2

For example I Have this example code:

class Player
{
   int grid;
   Player()
   {
      grid = 0;
   }

}
void main()
{
   Player p;
   ...
   ...
   //now again I want to initialize p here, what to write ?
}

How do I call the constructor of p again ?

Anubha
  • 1,345
  • 6
  • 23
  • 35

4 Answers4

5

Put the object into a local scope:

while (running)
{
    Player p;  // fresh

    //...
}

Each time the loop body executes, a new Player object is instantiated.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
4
class Player
{
   int grid;
   Player()
   {
      grid = 0;
   }

}
void main()
{
   Player p;
   ...
   ...
   //now again I want to initialize p here, what to write ?
   p = Player();
}
user1052842
  • 121
  • 1
  • 11
  • 2
    Although, to make this work correctly, you may have to implement the assignment operator (which isn't always simple or desirable). Often the simplest and most efficient thing is just to destroy the old object and allocate a new one. – Matteo Italia Aug 09 '12 at 13:43
  • That constructor is very poor practice (as is `void main`). You should really be using initializer lists. – Kerrek SB Aug 09 '12 at 14:48
3

Add init function. Call it in constructor, but also make it public, so you can call it later again.

Actually you can make any function you want to change the state:

class Player
{
public:
    void setState(/*anything you want*/) {}
};
Andrew
  • 24,218
  • 13
  • 61
  • 90
  • I think you are right, just thinking if the constructor cant be called again, instead of making a different function again... – Anubha Aug 09 '12 at 13:38
0

Reinforcing Andrew's answer:

class Player
{
public:
    Player()
    {
        reset(); //set initial values to the object
    }

    //Must set initial values to all relevant fields        
    void reset()
    {
        m_grid = 0; //inital value of "m_grid"
    }

private:
    int m_grid;
}


int main()
{
    Player p1;
    Player* p2 = new Player();

    ...
    ...
    p1.reset(); 
    p2->reset(); //Reset my instance without create a new one.
}