Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use int as an argument for post-increment operator overload?

As I know here is the way to overload the post-increment operator:

const MyClass& MyClass::operator++(int);

Why does it have int as an argument?

like image 332
Nayana Adassuriya Avatar asked Oct 05 '12 06:10

Nayana Adassuriya


2 Answers

D&E, §11.5.3:

I conisdered the obvious solution, adding the keywords prefix and postfix to C++ [ ... ] However I received the usual howl of outrage from people who dislike new keywords. Several alternatives that did not involve new keywords were suggested. For example:

   class Ptr_to_X {
       X ++operator(); // prefix ++
       X operator++(); // postfix ++
   };

or

   class Ptr_to_X {
       X& operator++(); // postfix because it 
                        // returns a reference
       x operator++();  // prefix because it
                        // doesn't return a reference
   };

I considered the former too cute and the latter too subtle. Finally I settled on:

   class Ptr_to_X {
       X operator++();     // prefix: no argument
       X operator++(int);  // postfix: because of the argument
   };

This may be too cute and too subtle, but it works, requires no new syntax, and has a logic to the madness. Other unary operators are prefix and take no arguments when defined as member functions. The "odd" and unused dummy int argument is used to indicate the odd postfix operators. In other words, in the postfix case, ++ comes between the first (real) operand and the second (dummy) argument and is thus postfix.

These explanations are needed because the mechanism is unique, and therefore a bit of a wart. Given a choice I would probably have introduced the prefix and postfix keywords, but that didn't appear feasible at the time.

like image 82
Jerry Coffin Avatar answered Sep 20 '22 01:09

Jerry Coffin


This is to distinguish between prefix increment and postfix increment operators.

For completeness, this is set out in §13.5.7 in both the C++03 and the C++11 standards.

like image 41
juanchopanza Avatar answered Sep 19 '22 01:09

juanchopanza