Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

8.13. Overloading the Increment and Decrement Operators

Problem

You have a class where the familiar increment and decrement operators make sense, and you want to overload operator++ and operator-- to make incrementing and decrementing objects of your class easy and intuitive to users.

Solution

Overload the prefix and postfix forms of ++ and -- to do what you want. Example 8-14 shows the conventional technique for overloading the increment and decrement operators.

Example 8-14. Overloading increment and decrement

#include <iostream>

using namespace std;

class Score {
public:
   Score() : score_(0) {}
   Score(int i) : score_(i) {}

   Score& operator++() { // prefix
      ++score_;
      return(*this);
   }
   const Score operator++(int) { // postfix
      Score tmp(*this);
      ++(*this); // Take advantage of the prefix operator
      return(tmp);
   }
   Score& operator--() {
      --score_;
      return(*this);
   }
   const Score operator--(int x) {
      Score tmp(*this);
      --(*this);
      return(tmp);
   }
   int getScore() const {return(score_);}

private:
   int score_;
};

int main() {
   Score player1(50);

   player1++;
   ++player1; // score_ = 52
   cout << "Score = " << player1.getScore() << '\n';
   (--player1)--; // score_ = 50
   cout << "Score = " << player1.getScore() << '\n';
}

Discussion

The increment and decrement operators often make sense for classes that represent some sort of integer value. They are easy to use, as long as you understand the difference between prefix and postfix and you follow the conventions for return values.

Think about incrementing an integer. For ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page