C++ Operator Overloading

Operator overloading is a type of polymorphism in which a single operator is overloaded to give user defined meaning to it. Operator overloading provides a flexibility option for creating new definitions of C++ operators. There are some C++ operators which we can't overload.

The lists of such operators are:
  • Class member access operator (. (dot), .* (dot-asterisk))
  • Scope resolution operator (::)
  • Conditional Operator (?:)
  • Size Operator (sizeof)

These are the lists of few excluded operators and are very few when compared to large sets of operators which can be used for the concept of operator overloading. An overloaded operator is used to perform an operation on the user-defined data type. Let us take an example of the addition operator (+) operator has been overloaded to perform addition on various variable types, like for integer, floating point, String (concatenation) etc.

return type className :: operator op (arg_list)
 //Function body;

Here, the return type is the type of value returned by the specified operation and op is the operator being overloaded.

Here is a program for Operator Overloading

#include <iostream>
using namespace std;

class MinusOverload {
 int a;
 int b;

 void Distance()
 a = 0;
 b = 0;

 MinusOverload(int f, int i)
 int c;
 a = f;
 b = i;
 c = a - b;
 cout << "\nC:" << c;

 void display()
 cout << "A: " << a << " B:" << b << endl;

 MinusOverload operator-()
 a = -a;
 b = -b;
 return MinusOverload(a, b);

int main()
 MinusOverload M1(6, 8), M2(-3, -4);
 return 0;