Cpp - Overload postfix and prefix operator

Introduction

The way to overload prefix and postfix operator is to include a int variable to the operator++() member function.

The integer won't be used; it's just a signal that the function defines the postfix operator.

The prefix operator changes a variable's value before returning it in expressions.

The postfix operator returns the value before incrementing or decrementing it.

To do this, in an overloaded member function, a temporary object must be created to hold the original value while the value of the original object is incremented.

The temporary object is returned because the postfix operator requires the original value, not the incremented value.

The temporary object must be returned by value and not by reference.

Otherwise, it goes out of scope as soon as the function returns.

Demo

#include <iostream> 
  
class Counter /* w  w w.j a  v  a2 s  .com*/
{ 
public: 
    Counter(); 
    ~Counter(){} 
    int getValue() const { return value; } 
    void setValue(int x) { value = x; } 
    const Counter& operator++();   // prefix 
    const Counter operator++(int); // postfix 
   
private: 
    int value; 
}; 
   
Counter::Counter(): 
value(0) 
{} 
 
const Counter& Counter::operator++() // prefix 
{ 
    ++value; 
    return *this; 
} 
 
const Counter Counter::operator++(int) // postfix 
{ 
    Counter temp(*this); 
    ++value; 
    return temp; 
} 
   
int main() 
{ 
    Counter c; 
    std::cout << "The value of c is " << c.getValue()  
           << std::endl; 
    c++; 
    std::cout << "The value of c is " << c.getValue()  
           << std::endl; 
    ++c; 
    std::cout << "The value of c is " << c.getValue()  
           << std::endl; 
    Counter a = ++c; 
    std::cout << "The value of a: " << a.getValue(); 
    std::cout << " and c: " << c.getValue() << std::endl; 
    a = c++; 
    std::cout << "The value of a: " << a.getValue(); 
    std::cout << " and c: " << c.getValue() << std::endl; 
    return 0; 
}

Result