Assigning an object address to another class

Hello, I'm having trouble understanding why this isn't working. As an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class house
{
     private:
          Person one;
          Person two;
     public:
          house(Person& first, Person& second)
          {
               one = first;
               two = second;
          }

          void changeinfo()
          {
               one.giveMoney(two);
               cout << two.getMoney() << endl;
          }
};

int main()
{
     house newhouse(john,jason);
     newhouse.changeinfo();
     cout << jason.getMoney() << endl;
     return 0;
}


Ok, in this example it shows the correct money in two.getMoney() cout in the class function but once i do it after that in main the object (jason) still has the same money he had before, meaning it is only taking a copy of Jason and it's just going away when the class method is called. I know if I change the method to changeinfo(Person& , Person&) instead of getting them in the constructor this works and the real info is changed of the object.

What am I doing wrong? I would like to have this class to where I import these two into "house" class and then have methods that can change their real values instead of just a copied one that goes away. Thanks.

Lines 9 and 10 above are using the assignment operator to create copies, meaning the private variables 'one' and 'two' in lines 4 and 5 are really just copies of the original persons passed to the house constructor in line 22.

In order to hold a reference, you must declare reference variables like this:

1
2
Person &one;
Person &two;


But note that reference variables can only be initialized in constructor lists, meaning you must change the constrcutor to be like this:

1
2
house(Person &first, Person &second) : one(first), two(second)
{ }


Check out the C++ tutorial at this site or some other site to fully understand the topic.
The issue is that copies are occurring here:

1
2
3
//in constructor
one = first;
two = second;


What you need to do is make one and two references to Person.

1
2
3
4
5
6
7
class house
{
   private:
      Person& one; //one is now a reference to Person
      Person& two; //two is now a refenece to Person

   ...


Then, you need to initialize one and two in the constructor's initialization list:

1
2
3
4
5
public:
   house(Person& first, Person& second)
      :   one(first), two(second)
   {
   }
Thanks for the quick response guys. I understand what you are saying.
Topic archived. No new replies allowed.