I recently came across a tricky situation in operator overloading. The idea is overload ++ operator for a class. Since ++ works as both prefix and postfix.
int x = 0; auto y = ++x; // This is prefix std::cout << "x: "<< x++ << "\n"; // this is postfix and value of // x is changed after the execution of this statement x = 1 std::cout << "y: " << y << "\n"; // y = 1
When it comes to overloading of ++ operator, things becomes little tricky. Following is the way to overload ++ operator for both prefix and postfix.
struct X{
int i = 0;
// The prefix is coded as ++x
X & operator++(){
++i;
return *this;
}
// this is postfix as x++
X operator ++(int){
X y(*this);
++y;
return y;
}
};
the prefix solution is straight forward but the postfix returns a copy of instance of X and hence its first copied, prefix increment is done and return the instance.
When overloading another operator << following code can be used.
struct X{ friend std::iostream& operator<<(std::iostream & os, const X & x){ os << "x.i: "<< x.i << "\n"; return os; } };