c++classreferenceoperator-overloadingpre-increment

Why does "cout << ++Object;" produce an error? (Both << and ++ have been overloaded)


In the code below, both << and ++ operators have been overloaded:

#include <iostream>
using namespace std;

class Test{
public:
    int num=0;
    Test operator++(){
      num++;
      return *this;
    }
};

ostream &operator<<(ostream &mystream, Test &x){
    mystream << x.num;
    return mystream;
}

When I increase the value of num inside the main(), using the expression ++a; before cout, the code executes completely fine:

int main(){
    Test a;
    ++a;
    cout << a << endl;
    return 0;
}

However, when I try to increase the value of num, after the << operator:

int main(){
    Test a;
    cout << ++a << endl;
    return 0;
}

The following error is being produced each time I run the code:

error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Test')
    cout << ++a << endl;
    ~~~~ ^  ~~~

Why does this happen and what could I do about this?


Solution

  • The prefix operator++ defined in your class:

    Test operator++(){
      num++;
      return *this;
    }
    

    returns a temporary object of the type Test.

    However, the overloaded operator<< expects an lvalue reference to an object of the class:

    ostream &operator<<(ostream &mystream, Test &x){
    

    You cannot bind an lvalue reference to a temporary object.

    You could, for example, either define the operator++ in the following way (and it should be defined that way):

    Test& operator++(){
      ++num;
      return *this;
    }
    

    Or/and define the operator<< in the following way:

    ostream &operator<<(ostream &mystream, const Test &x){
        mystream << x.num;
        return mystream;
    }
    

    providing a constant lvalue reference that can bind to a temporary object.