CS253: Software Development with C++

Spring 2022

Increment Decrement Methods

Show Lecture.IncrementDecrementMethods as a slide show.

CS253 Increment Decrement Methods

made at imgflip.com

Why

If you’re writing a class that is numeric or pointery, then it needs:

None of these come for free. You have to write them all.

Preincrement

Preincrement is easy:

    // Change the state of the object
    // Return the object by reference
    Whatever& operator++() {	    // No argument means preincrement
        // Do what is needed to change the object
        *this += 1;		    // just an example
        return *this;
    }

Postincrement

Postincrement is harder, but is the same for nearly all classes:

    // Save a copy of the object
    // Change the state of the object
    // Return the copy by value
    Whatever operator++(int) {	    // Dummy int arg means postincrement
        const auto save = *this;
        ++*this;		    // Call the preincrement method
        return save;
    }

Decrement & Guilt

Example

class ID {
  public:
    ID& operator++() {
        if (++s[1] > '5') {
            s[0]++; s[1] = '1';
        }
        return *this;
    }
    string s = "A1";
};

ID ident;
for (int i=0; i<12; i++)
    cout << (++ident).s << ' ';
A2 A3 A4 A5 B1 B2 B3 B4 B5 C1 C2 C3 

This class creates an ID object, and increments it several times. Since it’s preincrement, we never see A1. That requires postincrement.

Example using postincrement

class ID {
  public:
    ID& operator++() {
        if (++s[1] > '5') {
            s[0]++; s[1] = '1';
        }
        return *this;
    }
    string s = "A1";
};

ID ident;
for (int i=0; i<12; i++)
    cout << (ident++).s << ' ';  // 🦡
c.cc:14: error: no ‘operator++(int)’ declared for postfix ‘++’

Oh, yeah—we’ve got to actually write the postincrement method.

Example with postincrement

class ID {
  public:
    ID& operator++() {
        if (++s[1] > '5') {
            s[0]++; s[1] = '1';
        }
        return *this;
    }
    ID operator++(int) {
        const auto save = *this;
        ++*this;  // DRY!
        return save;
    }
    string s = "A1";
};

ID ident;
for (int i=0; i<12; i++)
    cout << (ident++).s << ' ';
A1 A2 A3 A4 A5 B1 B2 B3 B4 B5 C1 C2 

General Guidelines