Overloading The Increment And Decrement Operators


There are two versions:

  • A prefix increment and decrement (++x, x)
  • A postfix increment and decrement (x++, x)

Overloading prefix increment and decrement

Example 1: Note that we return *this. The overloaded increment and decrement operators return a Digit so multiple operators can be “chained” together. Consequently, we need to return an item of type Digit.

class Digit
    int m_nDigit;
    Digit(int nDigit=0)
        m_nDigit = nDigit;
    Digit& operator++();
    Digit& operator--();
    int GetDigit() const { return m_nDigit; }
Digit& Digit::operator++()
    // If our number is already at 9, wrap around to 0
    if (m_nDigit == 9)
        m_nDigit = 0;
    // otherwise just increment to next number
    return *this;
Digit& Digit::operator--()
    // If our number is already at 0, wrap around to 9
    if (m_nDigit == 0)
        m_nDigit = 9;
    // otherwise just decrement to next number
    return *this;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.