C++ Operator Overload unary prefix ++ operator

Introduction

Let us overload a unary prefix ++ operator for classes.

It is of signature MyClass& operator++():

#include <iostream> 
class MyClass //from w w w  . ja  v  a 2s .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; 
    } 
}; 

int main() 
{ 
    MyClass myobject; 
    // prefix operator 
    ++myobject; 
    // the same as: 
    myobject.operator++(); 
} 

In this example, when invoked in our class, the overloaded prefix increment ++ operator increments each of the member fields by one.




PreviousNext

Related