How to overload the operator++ in two different ways for postfix a++ and prefix ++a?

How to overload the operator++ in two different ways for postfix a++ and prefix ++a?


Solution 1:

Should look like this:

class Number 
{
    public:
        Number& operator++ ()     // prefix ++
        {
           // Do work on this.   (increment your object here)
           return *this;
        }

        // You want to make the ++ operator work like the standard operators
        // The simple way to do this is to implement postfix in terms of prefix.
        //
        Number  operator++ (int)  // postfix ++
        {
           Number result(*this);   // make a copy for result
           ++(*this);              // Now use the prefix version to do the work
           return result;          // return the copy (the old) value.
        }
}; 

Solution 2:

The difference lies in what signature you choose for your overload(s) of operator ++.

Cited from the relevant article on this subject in the C++ FAQ (go there for more details):

class Number {
  public:
    Number& operator++ ();     // prefix ++: no parameter, returns a reference
    Number  operator++ (int);  // postfix ++: dummy parameter, returns a value
};

P.S.: When I found out about this, all I saw initially was the dummy parameter, but the different return types are actually more interesting; they might explain why ++x is considered more efficient than x++ in general.