I’m trying to make a little pokemon game, that obviously includes attacking another pokemon. Don’t worry about Type; that’s just a ENUM.
Currently not working: The _reciever’s health doesn’t get changed, there are no errors
my current not working code:
class Pokemon
{
public:
string Name;
Type Type;
int Health;
Pokemon(string _name, Pokemons::Type _type, int _health)
{
Name = _name;
Type = _type;
Health = _health;
}
bool checkHealth()
{
if (Health <= 0)
{
return false;
}
return true;
}
void updateHealth(char _operator, int _amount)
{
switch (_operator)
{
case '+':
Health = Health + _amount;
break;
case '-':
Health = Health - _amount;
break;
case '*':
Health = Health * _amount;
break;
case '/':
Health = Health / _amount;
break;
}
}
void attackEnemy(Pokemon _reciever)
{
_reciever.Health = _reciever.Health - 5;
}
};
#include <iostream>
#include "Pokemon.h"
using namespace std;
using namespace Pokemons;
int main()
{
Pokemon Charmender("Charmender", Fire, 45);
Pokemon Bulbasaur("Bulbasaur", Water, 50);
while (true) {
Charmender.attackEnemy(Bulbasaur);
cout << Bulbasaur.Health << endl;
}
}
ps: this is my first ever stackoverflow question, do let me know if I missed something
>Solution :
Currently, you are accessing the other class member variables without problems, but your changes are not as intended because you are passing a copy of the object:
void attackEnemy(Pokemon _reciever)
{
_reciever.Health = _reciever.Health - 5;
}
With this approach, _receiver
goes away at the end of your method.
To get persistent changes, you can pass by reference:
void attackEnemy(Pokemon &_reciever)
{
_reciever.Health = _reciever.Health - 5;
}