c++ - 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 code (simplified illustrate problem) want access member variable money, inside company increase money of person. however, p.money += amount appears work locally, , not change value of money specific person in main.

what methods of making work? possible make money a protected member variable?

the function should accept object reference

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

otherwise function deals copy of object of type person.

you can make data member money private or protected (provided class nor final class) have define accessor change object.

for example

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

in case can write

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

it better declare member function get_money qualifier const. in case can used constant objects of class person.

int get_money() const {return money; } 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -