Search code examples
c++operator-overloadingassociativity

When does operator<< refer to the insertion operator and when to the bitwise left shift?


When does operator << refer to the insertion operator and when does it refer to the bitwise left shift?

This will output 10, and operator << refers to the left shift.

cout << a.b() << a.a.b << endl;  

And this will output 11, operator << refers to the insertion operator.

cout << a.b();
cout << a.a.b ;

I am confused, when will operator << (when use with cout) refer to the left shift operator?

#include <iostream> 
using namespace std; 

class A { 
public:
    A() { a.a = a.b = 1; }

    struct { int a, b; } a;

    int b(); 
}; 

int A::b(){
    int x=a.a;
    a.a=a.b;
    a.b=x; 
    return x;
};

 int main(){
    A a; 
    a.a.a = 0; 
    a.b(); 

    cout << a.b() << a.a.b << endl;      // ?????
    return 0;
}

Solution

  • The problem you are confronted with is not concerning the << operator. In each case, the insertion operator is called.

    However, you are faced with a problem concerning the order of evaluation in the command line

    cout << a.b() << a.a.b << endl;
    

    The function a.b() has a side effect. It swaps the values a.a.a and a.a.b. Thus, it is evident, wether a.b() is called before or after evaluating the value ov a.a.b.

    In C++, the order of evaluation is unspecified, see cppreference.com for a more detailed discussion.