I have a class Square , Player . Player consists of string name and another object XYZ.
Suppose i have to destroy player in the Square class.
Destroy means players name becomes NULL to show that there is no player on the square.
How should it be done?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Square
{
private :
Player player;
public :
Square(Player p)
{
player = p;
}
void destroy()
{
// what should come here?
// is it right? Why or why not
player = new Player("" , new XYZ());
}
};
@andy1992,
I know the method you posted.
Just wanted to know that my code is also correct or not .
And if it is correct, are there any issues with that approach?
class Player
{
void destroy()
{
name.clear();
delete pointer_to_xyz; // Note: nullptr or allocated by this class
pointer_to_xyz = nullptr;
}
};
...
class Square
{
private :
Player player;
public :
Square(Player p)
{
player = p;
}
void destroy()
{
player.destroy();
}
};
1. player is not a pointer player = new Player("" , new XYZ())///dont call XYZ constructor like that
2. There might be some memory leak.
3. Your function doesn't destroy anything, it allocates a new object instead so how did
you take care of the initial object.
i'll not recommend using dynamic memory coz you really have a lot to track but then there is an easier option-> smart pointers might be a little more friendly
@Coder i hadn't seen your post, i probably typed for sooooo long. :D
I so you can make a function to reset the state of the objects
for example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Player
{
public:
void reset()
{
///reset the variables you want
}
/// other members
private:
///others
};
int main()
{
Player pl;
pl.reset();///resets object to the default value
}