Operator Overloading in C++
1. When an operator is overloaded with multiple jobs, it is known as operator overloading.
2. Operator overloading is a way to implement compile time polymorphism.
3. Any symbol can be used as function name if
(a.) if it is a valid operator in C language.
(b.) if it is preceded by operator keyword.
4. We cannot overload sizeof operator and ternary (?:) operator.
For Example:-
#include<iostream> using namespace std; class Complex { private: int real, imaginary; public: void setData(int num1, int num2) { real = num1; imaginary = num2; } void showData() { cout << real << " " << imaginary; } Complex operator+(Complex C) //operator overloading of + symbol. { Complex temp; temp.real = real+C.real; temp.imaginary = imaginary+C.imaginary; return temp; } }; int main() { Complex C1,C2,C3; C1.setData(3,4); C2.setData(5,6); C3 = C1+C2; //calling operator overloading. C3.showData(); }
Output:
8 10
Overloading of Unary Operator
Operator which takes only one operand to perform operation is called unary operator. To know more about different types of operator, you should check this >> Operators
Unary operator can be overloaded as follows.
For Example:-
#include<iostream> using namespace std; class Complex { private: int real, imaginary; public: void setData(int num1, int num2) { real = num1; imaginary = num2; } void showData() { cout<< real << " " << imaginary; } Complex operator-() //operator overloading of unary operator -. { Complex temp; temp.real = -real; temp.imaginary = -imaginary; return temp; } }; int main() { Complex C1,C2; C1.setData(9,2); C2 = -C1; //C2=c1.operator-() calling unary operator overloading. C2.showData(); }
Output:
-9 -2
Pre and Post increment Operator Overloading
The symbol of prefix (++i) and postfix (i++) operator is same so we need to use a dummy int as parameter in postfix version to distinguish between the two functions definition.
For Example:-
#include<iostream> using namespace std; class Integer { private: int num; public: void setData(int a) { num = a; } void showData() { cout << "\n integer is: "<< num; } Integer operator++() //preincrement operator overloading. { Integer i; i.num = ++num; return i; } Integer operator++(int) //postincrement operator overloading. { Integer i; i.num = num++; return i; } }; int main() { Integer i1, i2; i1.setData(55); i1.showData(); i2 = i1++; //i2=i1.operator++() i2.showData(); i2 = ++i1; i2.showData(); }
Output:
integer is: 55 integer is: 55 integer is: 57
For more information: Operator overloading as a friend function, overloading of unary operator as a friend function, insertion and extraction operator overloading.
Read Here >> More on Operator Overloading