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

rookie picture rookie · Oct 2, 2010 · Viewed 89.3k times · Source

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

Answer

Martin York picture Martin York · Oct 2, 2010

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.
        }
};