Alexander Alexander - 23 days ago 6
C++ Question

Accessing and changing member variable within other class

#include <iostream>
#include <string>
using namespace std;

class Person
{
private:
string name;
public:
Person(string _name, int _money) : name(_name), money(_money) {}
int money;
int get_money() {return money; }
};

class Company
{
private:
string name;
public:
Company(string _name) : name(_name) {}
void pay_salary(Person p, int amount);
};

void Company::pay_salary(Person p, int amount)
{
p.money += amount;
}

int main()
{
Person bob("Bob", 0);
Company c("C");

cout << bob.get_money() << endl; // prints 0
c.pay_salary(bob,100);
cout << bob.get_money() << endl; // prints 0

return 0;
}


In this code (simplified to illustrate my problem) I want to access the member variable money, inside Company to increase the money of a Person. However, p.money += amount appears to only work locally, and does not change the value of money for the specific person in main.

What are some methods of making this work? Would it be possible to make money a a protected member variable?

Answer

The function should accept the object by reference

void pay_salary( Person &p, int amount);
                 ^^^^^^^^^

Otherwise the function deals with a copy of the object of type Person.

You can make the data member money private or protected (provided that the class is nor a final class) but you have to define an accessor that to change the object.

For example

void set_money( int money ) {this->money = money; }

In this case you can also write

void Company::pay_salary(Person &p, int amount)
{
    p.set_money( p.get_money() + amount );
}

It is better to declare the member function get_money with qualifier const. In this case it can be used for constant objects of the class Person.

int get_money() const {return money; }