The reason to return a reference to an object is to make the behavior the same as for integers (for built in types).
std::cout << ++i;
std::cout << i++;
If i
is an integer this will work. This will only work in a class if you return a reference to the object (Assuming you have defined operator<<
for your class).
class ABC {
int i;
public:
ABC(int x = 0) : i(x) {}
const ABC& operator++() { i=i+1; return *this;}
ABC operator++(int) { ABC result(*this);i=i+1; return result;}
friend std::ostream& operator<<(std::ostream& out, ABC const& val)
{
return out << val.i;
}
};
With this definition then your class will behave the same way that an integer will behave in the above situation. Which makes it very useful when using template as you can now do a drop in replacement for integer with your type.
Note normally I would return just a reference (not a const reference).
/*const*/ ABC& operator++() { i=i+1; return *this;}
^^^^^^^^^
see: https://stackoverflow.com/a/3846374/14065
But C++ allows you do anything and you can return whatever is useful or has appropriate meaning for the situation. You should consider what is meaningful for your class and return a value that is appropriate. Remember the Principle of lease surprise