What's going on guys. I have this issue will my output. I'm a little confused why the output isn't what I'm expecting. Bear with me it's a bit of code.
Enemy has attacked! - 10
-10 // I want health to be 90
I was thinking it has to do with the default constructor setting everything to 0, but shouldn't that be overwritten when I called the setHealth function in the main program? Thanks
The problem is twofold:
1. It is bad class design to directly display results. i.e. it is good practice to return values and not use the class to cin or cout. In this case it adds to the confusion. main is the right place for cout's and cin's.
2. Your implementation quite rightly differentiates hero's and enemy's but then goes on to confuse enemy::attack() by not clearly defining who is the attacker and who is the defender/hero. What this means is the enemy attack method should include a reference (parameter) regarding the identity of the hero. That way the hero's properties are amended, not the attackers. Should be something like enemy::attack( hero aHero, int someDamage);
> the default constructor setting everything to 0, but shouldn't that be
> overwritten when I called the setHealth function in the main program?
¿where do you set the health of the enemy `e'?
You have to pass by reference the object you want to perform the action on. Otherwise the compiler doesn't know you are trying to change the values of hero h in main and not some other hero.
Also, like others have said, this is a poorly designed class. You should consider rewriting it. But if you must use it this way, this is how you do it.
Ok I'll rewrite it. Anything else besides the cins and couts?
Thanks for the tips.
Also the cout << getHealth() << endl;
is not part of the final program. I just put it in to as a reference.
Ok I'll rewrite it.
Excellent. It is only a couple of lines. So you don't have to scrap anything much.
Anything else besides the cins and couts?
As long as you make the other changes to attack( ... ) you should get sensible results.
( Test out as an exercise for yourself whether it should be hero&, hero or const hero@, const hero in the parameter list. It's important to get that right. )
( The question also arises when a hero attacks an enemy )