CS253: Software Development with C++

Spring 2018

Increment Methods

See this page as a slide show

CS253: Increment Methods


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 is easy:

  1. Change the state of the object
  2. 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;

Fast & efficient—no copying is required.


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

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

Less efficient—need to make a copy, and return by value.


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

Modified: 2017-02-22T15:49

User: Guest

Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building