1

Trying overloading operator() in the following example:

#include <iostream>
using namespace std;

class Fib {
  public:
    Fib() : a0_(1), a1_(1) {}
    int operator()();
  private:
    int a0_, a1_;
};
int Fib::operator()() {
    int temp = a0_;
    a0_ = a1_;
    a1_ = temp + a0_;
    return temp;
}

int main() {
    Fib fib;

    cout << fib() <<"," << fib() << "," << fib() << "," << fib() << "," << fib() << "," << fib() << endl;
}

It prints the fib sequence in the reverse order as 8,5,3,2,1,1. I understand the states are kept in () overlading but why the printing is showing up in the reverse order?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
KKG10
  • 11
  • 2

1 Answers1

0

operator << is a some function defined for its parameters. The order of evaluation of function arguments is unspecified. They can be evaluated right to left or left to right. It seems your compiler evaluates them right to left.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks for the clarification.I was using g++ on cygwin and bsd. – KKG10 Apr 08 '15 at 21:41
  • @KKG10 You should split this one output statement into several statements. – Vlad from Moscow Apr 09 '15 at 04:54
  • I am not sure if this is correct. In my mind it should translate to ostream.operator<<(param1).operator<<(param2)...., therefore it should not only generate just 1 function call but multiples? Unless operator<< is somehow different – eucristian Jun 16 '22 at 15:55
  • 1
    @eucristian How are the function calls fib() evaluated in this line from left to right or from right to left before the C++ 17? The question demonstrates you the answer. – Vlad from Moscow Jun 16 '22 at 15:58