Why Operator Overloading Is Needed?
Why Operator Overloading Is Needed?
Need of Operator Overloading:
In C++, we can make operators work for classes specified by the user. The overloading of operators is an important concept. It is a form of polymorphism where an operator is overloaded to give a definite meaning to the user. Overloaded operator is used for user-defined data type operation. For example, operator ' + ' can be overloaded to add different types of data, such as Integer, String (concatenation) etc.
In C++, nearly every operator can be overloaded. There are, however, few operators that cannot be overloaded. Following are operators who are not overloaded:
- Scope operator(::)
- Sizeof()
- Member operator(.)
- Pointer(*)
- Ternary operator(?:)
Syntax of operator overloading:
ReturnType classname :: operator operatorSymbol (argument list)
{
//method body
}
Here operator is keyword. operatorSymbol is operator symbol to be overloaded.
Implementing Operator Overloading in C++:
Following is the c++ program which overloads (+) operator as addition for two complex numbers.
Step by step
Solved in 4 steps with 1 images