C++ Operator Overload unary postfix ++ operator

Introduction

To implement a postfix operator ++, we will implement it in terms of a prefix operator:

#include <iostream> 
class MyClass /*from  w w w.  j  a va2 s  . c o m*/
{ 
private: 
    int x; 
    double d; 

public: 
    MyClass() 
         : x{ 0 }, d{ 0.0 } 
    { 
    } 

    // prefix operator ++ 
    MyClass& operator++() 
    { 
        ++x; 
        ++d; 
        std::cout << "Prefix operator ++ invoked." << '\n'; 
        return *this; 
    } 

    // postfix operator ++ 
    MyClass operator++(int) 
    { 
        MyClass tmp(*this); // create a copy 
        operator++();       // invoke the prefix operator overload 
        std::cout << "Postfix operator ++ invoked." << '\n'; 
        return tmp;         // return old value 
    } 
}; 

int main() 
{ 
    MyClass myobject; 

    // postfix operator 
    myobject++; 
    // is the same as if we had: 
    myobject.operator++(0); 
} 

Please do not worry too much about the somewhat inconsistent rules for operator overloading.

Remember, each (set of) operator has its own rules for overloading.




PreviousNext

Related