Home > Net >  How can I change an object's attributes with function?
How can I change an object's attributes with function?

Time:11-27

Forgive me if the title isn't specific enough. Let's say I want to make an RPG. I make a class for the characters. I then make an array that function as a party of characters. Then I have a function that reduced the HP of the first member of a party.

`

#include <iostream>
#include <string>

class Chara
    {
    public:
        int HP;
        Chara(int health)
        {
            HP = health;
        }
    };

int Battle(Chara Party[2])
    {
        Party[0].HP -= 2;
    }

int main()
{
    Chara Final(0);
    Chara Fantasy(7);

    Chara Player[2] = {Final, Fantasy};

    Battle(Player);
    std::cout << Final.HP;
}

`

However, the HP of the character doesn't change. Is there something that I can do to make it so that the character's HP actually changes?

CodePudding user response:

You have two separate problems caused by C passing structs by copy.

First, the line Chara Player[2] = {Final, Fantasy}; creates an array of Chara and initializes the members with copies of the mentioned variables. That means that the final line will not see any modifications made to elements of Player. Instead, you should do:

Chara Player[2] = { Chara{0}, Chara{7} };
// and optionally, if you still want to access individual members:
Chara& Final = Player[0];
Chara& Fantasy = Player[1];

Secondly, you pass Player to the Battle function by copy. Thus, any changes made to Party inside the function are not reflected in the outer Player variable. The quick fix is to take Party by pointer instead:

void Battle(Chara* Party) { ... }

This works because arrays can decay to pointers to their first element when passed.

As best practice, you should probably use a std::vector instead, which allows you to dynamically add and remove party members and has all kinds of helpful methods.

  • Related