CS253: Software Development with C++

Fall 2019

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
        // which might be *this += 1;
        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

Pre-/post-decrement is essentially the same. Get pre-/post-increment working, and then (I can’t believe that I’m saying this) use copy & paste.

General Guidelines