Why does the postfix increment operator take a dummy parameter?

Naruto picture Naruto · Aug 26, 2010 · Viewed 10.6k times · Source

Have a look at these function signatures:

 class Number {
 public:
   Number& operator++ ();    // prefix ++
   Number  operator++ (int); // postfix ++
 }; 

Prefix doesn't take any parameter but postfix does. Why? I thought we can recognize them with different return types.

Answer

Omnifarious picture Omnifarious · Aug 26, 2010

Prefix and postfix ++ are different operators. With the standard Foo operator symbol(Foo &) style declaration there was no obvious way to distinguish the two. Rather than come up with some new syntax like Foo symbol operator(Foo &) which would make it into a special case unlike all the other operators and likely a bit of a pain to parse, the language designers wanted some other solution.

The solution they chose was somewhat bizarre. They noted that all the other 'postfix' operators (i.e. operators that occurred after one of their operands) were actually infix operators that took two arguments. For example, plain old +, / or >. On this basis the language designers decided that having a random dummy argument would be a good way to distinguish between prefix and postfix ++.

IMHO, it's one of the stranger decisions made as C++ evolved. But there you have it.

And you can't distinguish them based on return type for two reasons.

The first is that functions in C++ cannot be overloaded on return type. You cannot have two functions that have identical names and parameter type lists but different return values.

The second is that method would not be robust or flexible enough to handle all possible implementations of prefix and postfix ++.

For example, you might want a postfix ++ that returned a reference type if the only reason you ever called it was to invoke a side-effect unrelated to the value of the variable you were applying it to. In my opinion, that would be a very bad implementation, but C++ is not about judging what kinds of stupid code you want to write, but about enabling you to write whatever code it is you think appropriate to the situation. And forcing you to use one particular style of return type for prefix ++ and postfix ++ would be contrary to that spirit.