Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a variable always equal to the result of some calculations?

Tags:

c++

c++11

In math, if z = x + y / 2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?

I mean something like that won't work, right?

int x; int y; int z{x + y}; cin >> x; cin >> y; cout << z; 

If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.

Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.

like image 415
Michael D. Blake Avatar asked Mar 28 '19 16:03

Michael D. Blake


People also ask

Can you set a variable equal to a function C++?

you cant set a function equal to a variable, you can set a variable equal to a functions return value or address though, the below example demonstrates both.


1 Answers

Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.


You mean something like this:

class Z {     int& x;     int& y; public:     Z(int& x, int& y) : x(x), y(y) { }     operator int() { return x + y; } }; 

The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:

int x, y; Z z(x, y); std::cin >> x >> y; if(std::cin) // otherwise, IO error! (e. g. bad user input)     std::cout << z << std::endl; 

Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...

like image 75
Aconcagua Avatar answered Sep 29 '22 07:09

Aconcagua