The canonical form of overloaded pre-increment and post-increment
operators for class Foo are declared in the following way in C++.
/// Preincrement operator
Foo & operator++ (void);
/// Postincrement operator
const Foo operator++ (int);
The int in the post-increment operator is obviously to disambiguate
between post and pre forms of the operator. Then, why is the return type
different? As many other C++ features, this one also has a subtle
In C++, for ints, you can write
++i = k;
i++ = k;
This is because, i++ results in a Rvalue to which you can't assign.
Unlike i++, ++i results in a Lvalue to which you can assign which
is infact ( incremented ) i itself. Not that ++i = k; has a great
importance, but it is a fact that C++ has been designed that way.
I would be interested in knowing the reason. One reason is that
i++ = k; is not allowed is that it is just ambiguous.
but ++i = k; is not ambiguous.
A const in the return type is also required to disallow passing
the return value of i++ to a function taking non-const parameters
by reference. e.g. bar (Foo &); .... bar (f++); The return value of
f++ (which is f) is not supposed to last beyond the function call.
Therefore, in C++ these semantics of basic types should be followed by user-defined types.
Unless you declare pre-increment operator to return a reference to *this
it will not completely mimic the above basic type semantics. It is quite
important to preserve the basic type semantics when you overload these
opertors because the client and the compiler expect that you indeed preserved them.