In C ++, when we create an object, the constructor initializes, but if I want to initialize the object again, tell me at some point in the main thing, what should I do?

For example, I have this code example:

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 p again?

+2
c ++ oop
Aug 09 2018-12-12T00:
source share
4 answers

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

In fact, you can make any function you want to change:

 class Player { public: void setState(/*anything you want*/) {} }; 
+3
Aug 09 2018-12-12T00:
source share
β€” -

Place the object in a local area:

 while (running) { Player p; // fresh //... } 

Each time the loop body is executed, a new Player object is created.

+5
Aug 09 2018-12-12T00:
source share
 class Player { int grid; Player() { grid = 0; } } void main() { Player p; ... ... //now again I want to initialize p here, what to write ? p = Player(); } 
+4
Aug 09 '12 at 13:40
source share

Reinforcement Andrew replies:

 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. } 
0
Aug 10 2018-12-12T00:
source share



All Articles