'I can't access to a value of my objectin C++
I'm starting C++ : I was trying to make my "player1" attack my "player2", to make him remove health to my "player2" and finally to display the health of "player2". But it's not working and I can't find the mistake. Here's my code I hope you will be able to help me:
PLAYER.CPP
class Player {
public:
std::string pseudo;
int healthValue = 100;
int attackValue = 5;
Player(std::string aPseudo) {
pseudo = aPseudo;
healthValue = healthValue;
attackValue = attackValue;
}
std::string getPseudo() {
return pseudo;
}
int getHealthValue() {
return healthValue;
}
int getAttackValue() {
return attackValue;
}
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
};
MAIN.CPP
#include "Player.cpp"
int main() {
Player player1("player1");
Player player2("player2");
std::cout << player2.getHealthValue() << std::endl;
player1.attack(player2);
std::cout << player2.getHealthValue() << std::endl;
return 0;
}
Solution 1:[1]
Here:
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
The parameter aTargetPlayer is passed by value, this means you decreased the health of a copy, not the original one. You must pass by reference, like this:
void attack(Player &aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
Solution 2:[2]
@JuanR's answer is valid. Note also that, they way you designed your class, the attack() method could very well be moved out of the class:
Why?
- The attacker does not have a stronger affinity to the code of the method than the attacked player. If anything, and since right now, the attack only affects the stats of the attacked player, you might have written a
getAttackedBy(const Player& other_player)... - The code for
attack()does not need access to protected or private members of thePlayerclass.
So consider writing:
void attack(Player& attacker, Player& attacked);
(This has both players passed by non-const reference in case you want to reduce the number of actions of the attacker, or allow it to take damage from the attacked player's defense etc.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JuanR |
| Solution 2 | einpoklum |
