PREV NEXT
What is operator overloading?
- In C++, operator overloading is a compile time polymorphism in which the operator is overloaded to provide the special meaning to the user defined data type.
- It is used to overload the operator in C++ and perform the operation on the user defined data type.
For example:
- we can overload the ‘+’ operator in a class like String so that we can concatenate two strings by using + and in other classes where arithmetic operators can be overloaded are fractional number, integer, etc.
- We can overload almost any operator in C++ but there are some of the operators which cannot be overloaded.
Such as:
- Member selector – (.)
- Ternary operator – (?:)
- Scope operator – (::)
- Member pointer selector – (*)
- Sizeof
How to implement operator overloading in C++?
The operator overloading can be done by implementing a function like:
- Member Function
- Non-member Function
- Friend Function
The operator overloading function can be a member function if the left operand is an object of that class but if the left operand is not an object then the operator overloading function must be a non-member function.
Operator overloading function can be made friend function if it need to access the private and protected members of class.
Let us have a look at the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <iostream> using namespace std; class Overloading { private: int n; public: Overloading(): n(8){} void operator ++() { n = n+4; } void Print() { cout<<"The Count is: "<<n; } }; int main() { Overloading o; ++o; // calling of a function "void operator ++()" o.Print(); return 0; } |
Some restrictions on Operator Overloading
Restrictions that should be considered while implementing operator overloading are:
- Number of operands cannot be changed like unary operators remains unary, binary remains binary, etc.
- Precedence and Associativity of an operator cannot be changes.
- No new operators can be created only the existing ones can be overloaded.