Operator Overloading in C++ : -
The mechanism of giving some special meaning to an operator is called as Operator Overloading.Â
When an operator is overloaded, it's original meaning is not lost. For example, the operator "+" has been overloaded to add two vectors, but it can still be used to add two integers.Â
Hence, when operator is overloaded then basically that operator performs some additional / special operation without losing it's original operation.Â
Also, when any operator is overloaded it behaves as a data-type. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using '+'
Some Instructions for Operator Overloading :Â
- Two operators ' = ' and ' & ' are already overloaded by default in C++.
- Both Unary and Binary operators can be overloaded in C++.
- When Unary operator is overloaded as a function then it does not return any value and does not takes an argument also.Â
- When Unary operator is overloaded as a friend function then it does not return any value but takes one argument as a parameter.
- When Binary operator is overloaded as a function then it returns a value and can take upto one argument as a parameter.
- When Binary operator is overloaded as a friend function then it returns a value and can take upto two argument as a parameter.
There are some operator which cannot be overloaded in C++ :-
- " sizeof " -Â size of operator
- " . "Â Â Â Â Â Â -Â member selection operator
- " :: "Â Â Â Â Â -Â scope resolution operator
- " ? : "Â Â Â Â - ternary operatorsÂ
Syntax of Operator Overloading : -Â
class className {
public
returnType operator symbol (arguments) {
}
};
Example of Operator Overloading : -
#include <iostream>
using namespace std;
class Increm
{
int num;
public:
setval(int n)
{
num = n;
}
Increm operator++()
{
num = num + 2;
}
void print()
{
cout << "The Incremented Value is : " << num;
}
};
int main()
{
int n;
cout << "Enter a number: ";
cin >> n;
Increm i;
i.setval(n);
++i;
i.print();
return 0;
}
OUTPUT:-
//ENJOY CODING\\
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP