+ 2

Help me with an explicit destructor call please

https://code.sololearn.com/c4bAqr5R44o9/?ref=app

2nd Apr 2023, 8:24 AM
Иван Паровозов
Иван Паровозов - avatar
3 Respostas
+ 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
2nd Apr 2023, 8:37 AM
Last
Last - avatar
+ 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.
2nd Apr 2023, 8:35 AM
Last
Last - avatar
+ 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
2nd Apr 2023, 1:26 PM
Bob_Li
Bob_Li - avatar