C++ execution order in method chaining

Moises Viñas picture Moises Viñas · May 16, 2016 · Viewed 9.9k times · Source

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?

Answer

Lightness Races in Orbit picture Lightness Races in Orbit · May 16, 2016

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);
}