Search code examples
c++classglobal-variablesfriend-function

Friend function how can i change their members globally


how can i change the members of a friend function globally, not just inside its block? i have a simple example below:

Expected Output(int): 45 35 35

#include<iostream>
using namespace std;

class dog
{
    private:
        int HealthPoints;
        int Damage;
    public:
    dog(int HealthPoints, int Damage){
        this->HealthPoints = HealthPoints;
        this->Damage = Damage;
    }
    friend void doAttack(dog,dog);
    int getHealthPoints(){return HealthPoints;}
    int getDamage(){return Damage;}
};

void doAttack(dog Attacker, dog Attacked){
    Attacked.HealthPoints = Attacked.HealthPoints - Attacker.Damage;
    cout << Attacked.HealthPoints << "\tvalue inside friend function" << endl;
}

int main()
{
    dog a(45, 10);
    dog b(45, 10);
    cout << b.getHealthPoints() << "\tvalue before friend function" << endl;
    doAttack(a, b);
    cout << b.getHealthPoints() << "\tvalue after friend function";
    return 0;
}

Solution

  • You don't want global variables. What you're currently doing is passing Attacker and Attacked by value - e.g. copying them. You make changes in doAttack to these copies. The originals are never modified. Pass them by reference instead.

    I have changed the name of your function to be more friendly as well. Feel free to change it back.

    void doPet(dog& Petter, dog& Petted) {
        Petted.LovePoints = Petted.LovePoints + Petter.Friendliness;
        cout << Petted.LovePoints << "\tvalue inside friend function" << endl;
    }