Operators Overloading in C++
Operators Overloading in C++
Operators overloading in C++ is a type of polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform operations on the user-defined data types.
However, there are a few operators which cannot be overloaded they are follows
-
- Scope operator – ::
- Sizeof
- Member selector – .
- Member pointer selector – *
- Ternary operator – ?:
Syntax of Operator overloading in C++
return_type class_name : : operator op(argument_list) { // body of the function. }
There are two types of Operator Overloading
-
- Unary Operator Overloading
- Binary Operator Overloading
1. Unary Operator Overloading
Unary operator overloading operates a single operand for example The increment (++) and decrement (–)
Program to overload the unary operator
#include <iostream> using namespace std; class Test { private: int num; public: Test(): num(5){} void operator ++() { num = num+2; } void Print() { cout<<"The Count is: "<<num; } }; int main() { Test tt; ++tt; tt.Print(); return 0; }
Output
The Count is: 7
2. Binary Operator Overloading
The binary operator overloading takes two arguments.The binary operators are addition (+), subtraction (-), division (/) operator etc.