Operator overloading means use of existing operators and perform a new task according to user-defined action.
We can overload all the CPP operators except the following:
Rules for Overloading Operators:
Operator overloading is defined like a function but with a operator keyword followed by a operator which you want to overload.
Types of Operator Overloading:
Unary operator works on just one operand. It takes no argument in the function definition. Unary operators are minus(-), increment(++), decrement(--)
Example 1: Input number and reverse the sign (if positive convert into negative, if negative convert into positive) using unary operator overload.
#include<iostream.h> #include<conio.h> class unary { int a; public: void input(); void output(); operator -() // unary operator defination { a=-a; } }; void unary::input() { cout<<"Enter Number: "; cin>>a; } void unary::output() { cout<<"Value = "<<a; } int main() { unary obj1; obj1.input(); -obj1; //operator minus(-) call obj1.output(); return 0; }
Binary Operator works on two operands. It takes only one argument in the function definition.
//calling syntax: c3=c1+c2 or c3=c1.operator+(c2)
Example 2: Input 2 numbers and find sum using binary operator overload.
class binary { int a; public: void input(); void output(); binary operator+(binary obj2){ binary obj3; obj3.a = a + obj2.a; return obj3; } }; void binary::input() { cout<<"Enter number: "; cin>>a; } void binary::output() { cout<<"Result = "<<a; } int main() { binary obj1, obj2, obj3; clrscr(); obj1.input(); obj2.input(); obj3 = obj1 + obj2; // operator overloading call obj3.output(); getch(); }
Operator overloading can be use using friend keyword. The only difference is that a friend opertor overloading requires two arguments in the operator definition.
//calling syntax: c3=c1+c2 or c3=operator+(c1,c2)