Search code examples
c++chainingoperator-precedence

C++ execution order in method chaining


The output of this program:

#include <iostream> 
class c1
{   
  public:
    c1& meth1(int* ar) {
      std::cout << "method 1" << std::endl;
      *ar = 1;
      return *this;
    }
    void meth2(int ar)
    {
      std::cout << "method 2:"<< ar << std::endl;
    }
};

int main()
{
  c1 c;
  int nu = 0;
  c.meth1(&nu).meth2(nu);
}

Is:

method 1
method 2:0

Why is nu not 1 when meth2() starts?


Solution

  • Because evaluation order is unspecified.

    You are seeing nu in main being evaluated to 0 before even meth1 is called. This is the problem with chaining. I advise not doing it.

    Just make a nice, simple, clear, easy-to-read, easy-to-understand program:

    int main()
    {
      c1 c;
      int nu = 0;
      c.meth1(&nu);
      c.meth2(nu);
    }