It is posible to automatically change the value of variables? For example: If i have 2 variables: "a" and "b", and let's say initially "a"= 3 and "b"= "a"+5;
If i change "a" = 7, how can i do that "b" automatically change its value according with "a"???
#ifndef _CLASS_H_
#define _CLASS_H_
class AandB
{
public:
AandB(int iniA) :
a(iniA)
{}
void setA(int val)
{
a = val;
}
int getA()
{
return a;
}
void setB(int val)
{
a = val - 5;
}
int getB()
{
return a + 5;
}
private:
int a;
};
#endif /* _CLASS_H_ */
#include <iostream>
int main()
{
AandB foo = AandB(3); //a is 3, b becomes 8
std::cout << "A is: " << foo.getA() << ", and B is: :" << foo.getB() << ".\n\n";
//set A to a new value
foo.setA(10); //b will now be 15;
std::cout << "Modifying A...\n\n";
std::cout << "A is: " << foo.getA() << ", and B is: " << foo.getB() << ".\n\n";
//set B to a new value
std::cout << "Modifying B...\n\n";
foo.setB(10); //a will now be 5
std::cout << "A is: " << foo.getA() << ", and B is: " << foo.getB() << ".\n\n";
return 0;
}
Output:
A is: 3, and B is: :8.
Modifying A...
A is: 10, and B is: 15.
Modifying B...
A is: 5, and B is: 10.