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












16















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;









share|improve this question









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • Why do you want to do that?

    – Robert Andrzejuk
    8 hours ago






  • 1





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    8 hours ago






  • 2





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Nay Wunna Zaw
    7 hours ago






  • 5





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    6 hours ago






  • 1





    That's called a "function."

    – ApproachingDarknessFish
    2 hours ago
















16















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;









share|improve this question









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • Why do you want to do that?

    – Robert Andrzejuk
    8 hours ago






  • 1





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    8 hours ago






  • 2





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Nay Wunna Zaw
    7 hours ago






  • 5





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    6 hours ago






  • 1





    That's called a "function."

    – ApproachingDarknessFish
    2 hours ago














16












16








16


4






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;









share|improve this question









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












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;






c++ c++11






share|improve this question









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 3 hours ago







Nay Wunna Zaw













New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 8 hours ago









Nay Wunna ZawNay Wunna Zaw

839




839




New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.













  • Why do you want to do that?

    – Robert Andrzejuk
    8 hours ago






  • 1





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    8 hours ago






  • 2





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Nay Wunna Zaw
    7 hours ago






  • 5





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    6 hours ago






  • 1





    That's called a "function."

    – ApproachingDarknessFish
    2 hours ago



















  • Why do you want to do that?

    – Robert Andrzejuk
    8 hours ago






  • 1





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    8 hours ago






  • 2





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Nay Wunna Zaw
    7 hours ago






  • 5





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    6 hours ago






  • 1





    That's called a "function."

    – ApproachingDarknessFish
    2 hours ago

















Why do you want to do that?

– Robert Andrzejuk
8 hours ago





Why do you want to do that?

– Robert Andrzejuk
8 hours ago




1




1





Right, that won't work. That's a spreadsheet thing.

– Pete Becker
8 hours ago





Right, that won't work. That's a spreadsheet thing.

– Pete Becker
8 hours ago




2




2





@RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

– Nay Wunna Zaw
7 hours ago





@RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

– Nay Wunna Zaw
7 hours ago




5




5





@NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

– Onyz
6 hours ago





@NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

– Onyz
6 hours ago




1




1





That's called a "function."

– ApproachingDarknessFish
2 hours ago





That's called a "function."

– ApproachingDarknessFish
2 hours ago












6 Answers
6






active

oldest

votes


















12














You can get close to this with by using a lambda in C++. Generally, when you set a variable like



int x;
int y;
int z{x + y};


z will only be the result of x + y at that time. You'd have to do z = x + y; every time you chnage x or y to keep it update.



If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



int x;
int y;
auto z = [&](){ return x + y; };
cin >> x;
cin >> y;
cout << z();


and now z() will have the correct value instead of the uninitialized garbage that the original code had.



If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



auto z = [&](){ static auto cache_x = x; 
static auto cache_y = y;
static auto cache_result = x + y;
if (x == cache_x && y == cache_y)
return cache_result;
else
{
cache_x = x;
cache_y = y;
cache_result = x + y;
reutrn cache_result;
}
};





share|improve this answer





















  • 2





    Shouldn't the caches have a type?

    – Aconcagua
    8 hours ago






  • 1





    Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

    – Max Langhof
    8 hours ago











  • And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

    – Mooing Duck
    2 hours ago











  • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

    – Fabio Turati
    1 hour ago











  • @FabioTurati See Aconcagua's answer

    – NathanOliver
    1 hour ago



















18














The closest you probably can get is to create a functor:



#include <iostream>

int main() {
int x;
int y;

auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

while(true) {
std::cin >> x;
std::cin >> y;
std::cout << z() << "n";
}
}





share|improve this answer































    8














    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;





    share|improve this answer































      2















      1. You create a function for that.

      2. You call the function with the appropriate arguments when you need the value.




      int z(int x, int y)
      {
      return (x + y);
      }


      int x;
      int y;

      // This does ot work
      // int z{x + y};

      cin >> x;
      cin >> y;
      cout << z(x, y);





      share|improve this answer



















      • 1





        yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

        – Nay Wunna Zaw
        8 hours ago











      • @NayWunnaZaw, yes, that is correct.

        – R Sahu
        8 hours ago






      • 1





        @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

        – R Sahu
        8 hours ago






      • 3





        @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

        – Aconcagua
        8 hours ago



















      2














      You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



      DEMO



      int x;
      int y;
      const auto z = [&x, &y](){ return x+y; };





      share|improve this answer





















      • 1





        Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

        – Aconcagua
        8 hours ago











      • @Aconcagua thx! you are right. I edited my answer.

        – Hiroki
        8 hours ago













      • Why downvoted ? At least I posted my answer faster than Ted with my tested code.

        – Hiroki
        1 hour ago



















      2














      There are two chief techniques:




      1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type.


      2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



      The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });






        Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.










        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55402807%2fhow-to-make-a-variable-always-equal-to-the-result-of-some-calculations%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        12














        You can get close to this with by using a lambda in C++. Generally, when you set a variable like



        int x;
        int y;
        int z{x + y};


        z will only be the result of x + y at that time. You'd have to do z = x + y; every time you chnage x or y to keep it update.



        If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



        int x;
        int y;
        auto z = [&](){ return x + y; };
        cin >> x;
        cin >> y;
        cout << z();


        and now z() will have the correct value instead of the uninitialized garbage that the original code had.



        If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



        auto z = [&](){ static auto cache_x = x; 
        static auto cache_y = y;
        static auto cache_result = x + y;
        if (x == cache_x && y == cache_y)
        return cache_result;
        else
        {
        cache_x = x;
        cache_y = y;
        cache_result = x + y;
        reutrn cache_result;
        }
        };





        share|improve this answer





















        • 2





          Shouldn't the caches have a type?

          – Aconcagua
          8 hours ago






        • 1





          Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

          – Max Langhof
          8 hours ago











        • And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

          – Mooing Duck
          2 hours ago











        • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

          – Fabio Turati
          1 hour ago











        • @FabioTurati See Aconcagua's answer

          – NathanOliver
          1 hour ago
















        12














        You can get close to this with by using a lambda in C++. Generally, when you set a variable like



        int x;
        int y;
        int z{x + y};


        z will only be the result of x + y at that time. You'd have to do z = x + y; every time you chnage x or y to keep it update.



        If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



        int x;
        int y;
        auto z = [&](){ return x + y; };
        cin >> x;
        cin >> y;
        cout << z();


        and now z() will have the correct value instead of the uninitialized garbage that the original code had.



        If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



        auto z = [&](){ static auto cache_x = x; 
        static auto cache_y = y;
        static auto cache_result = x + y;
        if (x == cache_x && y == cache_y)
        return cache_result;
        else
        {
        cache_x = x;
        cache_y = y;
        cache_result = x + y;
        reutrn cache_result;
        }
        };





        share|improve this answer





















        • 2





          Shouldn't the caches have a type?

          – Aconcagua
          8 hours ago






        • 1





          Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

          – Max Langhof
          8 hours ago











        • And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

          – Mooing Duck
          2 hours ago











        • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

          – Fabio Turati
          1 hour ago











        • @FabioTurati See Aconcagua's answer

          – NathanOliver
          1 hour ago














        12












        12








        12







        You can get close to this with by using a lambda in C++. Generally, when you set a variable like



        int x;
        int y;
        int z{x + y};


        z will only be the result of x + y at that time. You'd have to do z = x + y; every time you chnage x or y to keep it update.



        If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



        int x;
        int y;
        auto z = [&](){ return x + y; };
        cin >> x;
        cin >> y;
        cout << z();


        and now z() will have the correct value instead of the uninitialized garbage that the original code had.



        If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



        auto z = [&](){ static auto cache_x = x; 
        static auto cache_y = y;
        static auto cache_result = x + y;
        if (x == cache_x && y == cache_y)
        return cache_result;
        else
        {
        cache_x = x;
        cache_y = y;
        cache_result = x + y;
        reutrn cache_result;
        }
        };





        share|improve this answer















        You can get close to this with by using a lambda in C++. Generally, when you set a variable like



        int x;
        int y;
        int z{x + y};


        z will only be the result of x + y at that time. You'd have to do z = x + y; every time you chnage x or y to keep it update.



        If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



        int x;
        int y;
        auto z = [&](){ return x + y; };
        cin >> x;
        cin >> y;
        cout << z();


        and now z() will have the correct value instead of the uninitialized garbage that the original code had.



        If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



        auto z = [&](){ static auto cache_x = x; 
        static auto cache_y = y;
        static auto cache_result = x + y;
        if (x == cache_x && y == cache_y)
        return cache_result;
        else
        {
        cache_x = x;
        cache_y = y;
        cache_result = x + y;
        reutrn cache_result;
        }
        };






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 8 hours ago

























        answered 8 hours ago









        NathanOliverNathanOliver

        97.1k16137213




        97.1k16137213








        • 2





          Shouldn't the caches have a type?

          – Aconcagua
          8 hours ago






        • 1





          Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

          – Max Langhof
          8 hours ago











        • And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

          – Mooing Duck
          2 hours ago











        • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

          – Fabio Turati
          1 hour ago











        • @FabioTurati See Aconcagua's answer

          – NathanOliver
          1 hour ago














        • 2





          Shouldn't the caches have a type?

          – Aconcagua
          8 hours ago






        • 1





          Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

          – Max Langhof
          8 hours ago











        • And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

          – Mooing Duck
          2 hours ago











        • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

          – Fabio Turati
          1 hour ago











        • @FabioTurati See Aconcagua's answer

          – NathanOliver
          1 hour ago








        2




        2





        Shouldn't the caches have a type?

        – Aconcagua
        8 hours ago





        Shouldn't the caches have a type?

        – Aconcagua
        8 hours ago




        1




        1





        Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

        – Max Langhof
        8 hours ago





        Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

        – Max Langhof
        8 hours ago













        And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

        – Mooing Duck
        2 hours ago





        And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

        – Mooing Duck
        2 hours ago













        @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

        – Fabio Turati
        1 hour ago





        @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

        – Fabio Turati
        1 hour ago













        @FabioTurati See Aconcagua's answer

        – NathanOliver
        1 hour ago





        @FabioTurati See Aconcagua's answer

        – NathanOliver
        1 hour ago













        18














        The closest you probably can get is to create a functor:



        #include <iostream>

        int main() {
        int x;
        int y;

        auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

        while(true) {
        std::cin >> x;
        std::cin >> y;
        std::cout << z() << "n";
        }
        }





        share|improve this answer




























          18














          The closest you probably can get is to create a functor:



          #include <iostream>

          int main() {
          int x;
          int y;

          auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

          while(true) {
          std::cin >> x;
          std::cin >> y;
          std::cout << z() << "n";
          }
          }





          share|improve this answer


























            18












            18








            18







            The closest you probably can get is to create a functor:



            #include <iostream>

            int main() {
            int x;
            int y;

            auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

            while(true) {
            std::cin >> x;
            std::cin >> y;
            std::cout << z() << "n";
            }
            }





            share|improve this answer













            The closest you probably can get is to create a functor:



            #include <iostream>

            int main() {
            int x;
            int y;

            auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

            while(true) {
            std::cin >> x;
            std::cin >> y;
            std::cout << z() << "n";
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 8 hours ago









            Ted LyngmoTed Lyngmo

            3,5802522




            3,5802522























                8














                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;





                share|improve this answer




























                  8














                  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;





                  share|improve this answer


























                    8












                    8








                    8







                    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;





                    share|improve this 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;






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 8 hours ago









                    AconcaguaAconcagua

                    12.9k32144




                    12.9k32144























                        2















                        1. You create a function for that.

                        2. You call the function with the appropriate arguments when you need the value.




                        int z(int x, int y)
                        {
                        return (x + y);
                        }


                        int x;
                        int y;

                        // This does ot work
                        // int z{x + y};

                        cin >> x;
                        cin >> y;
                        cout << z(x, y);





                        share|improve this answer



















                        • 1





                          yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                          – Nay Wunna Zaw
                          8 hours ago











                        • @NayWunnaZaw, yes, that is correct.

                          – R Sahu
                          8 hours ago






                        • 1





                          @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                          – R Sahu
                          8 hours ago






                        • 3





                          @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                          – Aconcagua
                          8 hours ago
















                        2















                        1. You create a function for that.

                        2. You call the function with the appropriate arguments when you need the value.




                        int z(int x, int y)
                        {
                        return (x + y);
                        }


                        int x;
                        int y;

                        // This does ot work
                        // int z{x + y};

                        cin >> x;
                        cin >> y;
                        cout << z(x, y);





                        share|improve this answer



















                        • 1





                          yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                          – Nay Wunna Zaw
                          8 hours ago











                        • @NayWunnaZaw, yes, that is correct.

                          – R Sahu
                          8 hours ago






                        • 1





                          @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                          – R Sahu
                          8 hours ago






                        • 3





                          @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                          – Aconcagua
                          8 hours ago














                        2












                        2








                        2








                        1. You create a function for that.

                        2. You call the function with the appropriate arguments when you need the value.




                        int z(int x, int y)
                        {
                        return (x + y);
                        }


                        int x;
                        int y;

                        // This does ot work
                        // int z{x + y};

                        cin >> x;
                        cin >> y;
                        cout << z(x, y);





                        share|improve this answer














                        1. You create a function for that.

                        2. You call the function with the appropriate arguments when you need the value.




                        int z(int x, int y)
                        {
                        return (x + y);
                        }


                        int x;
                        int y;

                        // This does ot work
                        // int z{x + y};

                        cin >> x;
                        cin >> y;
                        cout << z(x, y);






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered 8 hours ago









                        R SahuR Sahu

                        170k1294193




                        170k1294193








                        • 1





                          yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                          – Nay Wunna Zaw
                          8 hours ago











                        • @NayWunnaZaw, yes, that is correct.

                          – R Sahu
                          8 hours ago






                        • 1





                          @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                          – R Sahu
                          8 hours ago






                        • 3





                          @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                          – Aconcagua
                          8 hours ago














                        • 1





                          yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                          – Nay Wunna Zaw
                          8 hours ago











                        • @NayWunnaZaw, yes, that is correct.

                          – R Sahu
                          8 hours ago






                        • 1





                          @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                          – R Sahu
                          8 hours ago






                        • 3





                          @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                          – Aconcagua
                          8 hours ago








                        1




                        1





                        yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                        – Nay Wunna Zaw
                        8 hours ago





                        yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                        – Nay Wunna Zaw
                        8 hours ago













                        @NayWunnaZaw, yes, that is correct.

                        – R Sahu
                        8 hours ago





                        @NayWunnaZaw, yes, that is correct.

                        – R Sahu
                        8 hours ago




                        1




                        1





                        @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                        – R Sahu
                        8 hours ago





                        @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                        – R Sahu
                        8 hours ago




                        3




                        3





                        @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                        – Aconcagua
                        8 hours ago





                        @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                        – Aconcagua
                        8 hours ago











                        2














                        You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                        DEMO



                        int x;
                        int y;
                        const auto z = [&x, &y](){ return x+y; };





                        share|improve this answer





















                        • 1





                          Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                          – Aconcagua
                          8 hours ago











                        • @Aconcagua thx! you are right. I edited my answer.

                          – Hiroki
                          8 hours ago













                        • Why downvoted ? At least I posted my answer faster than Ted with my tested code.

                          – Hiroki
                          1 hour ago
















                        2














                        You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                        DEMO



                        int x;
                        int y;
                        const auto z = [&x, &y](){ return x+y; };





                        share|improve this answer





















                        • 1





                          Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                          – Aconcagua
                          8 hours ago











                        • @Aconcagua thx! you are right. I edited my answer.

                          – Hiroki
                          8 hours ago













                        • Why downvoted ? At least I posted my answer faster than Ted with my tested code.

                          – Hiroki
                          1 hour ago














                        2












                        2








                        2







                        You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                        DEMO



                        int x;
                        int y;
                        const auto z = [&x, &y](){ return x+y; };





                        share|improve this answer















                        You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                        DEMO



                        int x;
                        int y;
                        const auto z = [&x, &y](){ return x+y; };






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 8 hours ago

























                        answered 8 hours ago









                        HirokiHiroki

                        2,1253320




                        2,1253320








                        • 1





                          Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                          – Aconcagua
                          8 hours ago











                        • @Aconcagua thx! you are right. I edited my answer.

                          – Hiroki
                          8 hours ago













                        • Why downvoted ? At least I posted my answer faster than Ted with my tested code.

                          – Hiroki
                          1 hour ago














                        • 1





                          Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                          – Aconcagua
                          8 hours ago











                        • @Aconcagua thx! you are right. I edited my answer.

                          – Hiroki
                          8 hours ago













                        • Why downvoted ? At least I posted my answer faster than Ted with my tested code.

                          – Hiroki
                          1 hour ago








                        1




                        1





                        Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                        – Aconcagua
                        8 hours ago





                        Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                        – Aconcagua
                        8 hours ago













                        @Aconcagua thx! you are right. I edited my answer.

                        – Hiroki
                        8 hours ago







                        @Aconcagua thx! you are right. I edited my answer.

                        – Hiroki
                        8 hours ago















                        Why downvoted ? At least I posted my answer faster than Ted with my tested code.

                        – Hiroki
                        1 hour ago





                        Why downvoted ? At least I posted my answer faster than Ted with my tested code.

                        – Hiroki
                        1 hour ago











                        2














                        There are two chief techniques:




                        1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type.


                        2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                        The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






                        share|improve this answer




























                          2














                          There are two chief techniques:




                          1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type.


                          2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                          The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






                          share|improve this answer


























                            2












                            2








                            2







                            There are two chief techniques:




                            1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type.


                            2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                            The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






                            share|improve this answer













                            There are two chief techniques:




                            1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type.


                            2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                            The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 5 hours ago









                            Toby SpeightToby Speight

                            17.2k134367




                            17.2k134367






















                                Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.










                                draft saved

                                draft discarded


















                                Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.













                                Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.












                                Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.
















                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55402807%2fhow-to-make-a-variable-always-equal-to-the-result-of-some-calculations%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to make a Squid Proxy server?

                                Is this a new Fibonacci Identity?

                                Touch on Surface Book