Operator overloading is a type of polymorphism in which a single operator is overloaded to give a user-defined meaning. Operator overloading provides a flexible option for creating new definitions of C++ operators.
There are some C++ operators which we can't overload.
- Class member access operator (
.
(dot),.*
(dot-asterisk)) - Scope resolution operator (
::
) - Conditional Operator (
?:
) - Size Operator (
sizeof
)
These are the lists of a few excluded operators and are very few compared to large sets of operators that can be used for operator overloading. An overloaded operator is used to operate on the user-defined data type. Let us take an example of the addition operator (+
) operator that has been overloaded to perform addition on various variable types, like integer, floating point, String (concatenation), etc.
Syntax:
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 an example program for operator overloading:
Example:
#include <iostream>
using namespace std;
class MinusOverload {
private:
int a;
int b;
public:
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);
-M1;
M1.display();
-M2;
M2.display();
return 0;
}