Automatic change of variable value

Hello,

Need a litle help with a problem.

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"???
Make b a function of a, but then it wouldn't be a variable.
Last edited on
This is one of the common mistakes among beginners. Operations are always performed sequentially rather than symbolically.
closed account (1yR4jE8b)
You could use a class:

AandB.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#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.
Topic archived. No new replies allowed.