Cpp - Operator Overloading Introduction

Introduction

When you implement an operator for a class, you are overloading that operator.

The most common way to overload an operator in a class is to use a member function.

The function declaration takes this form:

returnType operatorsymbol(parameter list) 
{ 
   // body of overloaded member function 
} 

The name of the function is operator keyword followed by the operator symbol, such as + or ++.

The?returnType is the function's return type.

The parameter list holds zero, one, or two parameters (depending on the operator).

The following code shows how to overload the increment operator ++.

Demo

#include <iostream> 
  
class Counter /*from  www .j a  v a  2 s  .  c  o m*/
{ 
public: 
    Counter(); 
    ~Counter(){} 
    int getValue() const { return value; } 
    void setValue(int x) { value = x; } 
    void increment() { ++value; } 
    const Counter& operator++(); 
   
private: 
    int value; 
}; 
   
Counter::Counter(): 
value(0) 
{} 
 
const Counter& Counter::operator++() 
{ 
    ++value; 
    return *this; 
} 
   
int main() 
{ 
    Counter c; 
    std::cout << "The value of c is " << c.getValue()  
            << std::endl; 
    c.increment(); 
    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; 
    return 0; 
}

Result