+ 2
Help me with an explicit destructor call please
3 Respuestas
+ 3
To fix this problem, you should not call the destructor explicitly inside the class method. Instead, you can use the delete keyword outside of the class to explicitly destroy the object. Here is an updated code example:
https://code.sololearn.com/cnGQl1tcu9VC/?ref=app
+ 2
The problem with the code is that the destructor is called twice. When the get_damage method is called, the condition if (health <= 0) is true and it calls the destructor explicitly using this-> ~Human(). However, after the get_damage method is finished, the destructor is also called implicitly for the object man as it goes out of scope. This is the reason why the output shows "bye!" twice.
+ 1
Иван Паровозов
One problem with using destructors this way is that it raises an error if you called an object after it is destroyed.
(But maybe it would not be a problem if your game makes it inaccessible after it is destroyed)
Anyway, I think it is more robust to just use an alive boolean instead. Just make the object stop responding if it is dead.
https://code.sololearn.com/cvpi1S9875aP/?ref=app