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 ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.