This sounds like the XY problem (pun intended).
From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.
Before I go into that, note that assignment is distinct from an equality relation. The =
in C++ is assignment, which is not the same as the =
in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".
Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:
class Player {
std::vector<int> inventory;
int cash;
public:
int inventory_total();
int net_worth();
}
//adds up total value of inventory
int Player::inventory_total() {
int total = 0;
for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
total += *it;
}
return total;
}
//calculates net worth
int Player::net_worth() {
//we are using inventory_total() as if it were a variable that automatically
//holds the sum of the inventory values
return inventory_total() + cash;
}
...
//we are using net_worth() as if it were a variable that automatically
//holds the sum of the cash and total holdings
std::cout << player1.net_worth();
I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y
, but it really is only a few extra lines of code.
That would be very annoying and error prone if you forgot to call the function somewhere.
In this case the object doesn't have a net_worth
member variable, so you can't accidentally use it instead of calling the function.