0

How can I permanently change a class's member?

I have a class, Hero, with a public health member and a takeHit function, like this: class Hero { public: Hero(int hp) : health(hp) { } int takeHit(int damage) { health = health - damage; return health; } }; int main() { Hero superhero(120); superhero.takeHit(20); cout << superhero.health << endl; return 0; } The problem is, the value returned by the function is correct, but when I cout superhero.health, it outputs the initial value of health. How can I permanently change the health member?

17th Aug 2018, 12:35 AM
jacksonofgames 28
jacksonofgames 28 - avatar
3 Réponses
+ 1
Sorry, I thought that example would behave the same way my real problem code does. Here is the code that's actually causing the problem https://code.sololearn.com/c2596vrjm5c8/?ref=app
19th Aug 2018, 2:08 AM
jacksonofgames 28
jacksonofgames 28 - avatar
0
jacksonofgames 28 , with your code, I expected to health to be 100 (120-20) and it does print 100 when I checked on code playground.... what is issue I don't get... it is not printing initial value 120...
17th Aug 2018, 5:19 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
class Hero { public: int health; Hero(int hp){ (*this).health=hp; } void takeHit(int damage) { (*this).health = (*this).health - damage; } }; #include <iostream> using namespace std; int main() { Hero superhero(120); superhero.takeHit(20); cout << superhero.health << endl; return 0; } Changed it a bit, prints out 100 for me :P
17th Aug 2018, 7:32 AM
MarJan
MarJan - avatar