Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: How do I access a variable from another class definition

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
        }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading