I am passing the Person object as a argument to the TimesTwo constructor and the PlusTen constructor. Both of these classes point to the same PersonObject. When I change the int age field in the PersonObj, The information return by TimesTwo and PlusTen should also change, but PlusTen is not returning the expected value.
#include <iostream>
using namespace std;
class PersonObj
{
public:
int age;
PersonObj(int x)
{
age = x;
}
int getAge()
{
return age;
}
void setAge(int x)
{
age =x;
}
};
class TimesTwo
{
public:
PersonObj *person;
TimesTwo(PersonObj p)
{
person = &p;
}
int getAgeTimesTwo()
{
return person->getAge() * 2;
}
};
class PlusTen
{
public:
PersonObj *person;
PlusTen(PersonObj p)
{
person = &p;
}
int getAgePlusTen()
{
return person->getAge() + 10;
}
};
int main()
{
int num;
PersonObj person(25);
TimesTwo t(person);
PlusTen p(person);
num = t.getAgeTimesTwo();
cout << "Person's age * 2 = " << num <<endl;
num = p.getAgePlusTen();
cout << "Person's age + 10 = " << num <<endl;
person.setAge(28); // Change/Set person's age to 26
num = t.getAgeTimesTwo();
cout << "Person's age * 2 = " << num <<endl;
num = p.getAgePlusTen();
cout << "Person's age + 10 = " << num <<endl;
return 0;
}
Output:
Person's age * 2 = 50
Person's age + 10 = 4199934
Person's age * 2 = 56
Person's age + 10 = 4199934