Operator Overloading
Operator Overloading
Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data
type. The mechanism of giving such special meanings to an operator is known as
operator overloading.
Operator overloading facilitates the specification of user-defined implementation
for operations wherein one or both operands are of user-defined class or
structure type. This helps user-defined types to behave much like the
fundamental primitive data types. Operator overloading is helpful in cases where
the operators used for certain types provide semantics related to the domain
context and syntactic support as found in the programming language. It is used
for syntactical convenience, readability and maintainability.
For Example:
The below code can be replace from,
calculation = add(multiply(a, b),divide(a, b));
to
calculation = (a*b)+(a/b);
To overload an operator, a special operator function is defined inside the class as:
class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};
class Test
private:
int count;
public:
Test(): count(5){}
count = count+1;
};
int main()
{
Test t; // this calls "function void operator ++()" function
++t;
t.Display();
return 0;
Output
Count: 6
Unary Operator Overloading:
The unary operators are those operators that requires only one operand to
perform different kind of operations such as increasing/decreasing a value,
negating a value etc. And overloading of such operators is called unary operator
overloading.
For e.g. unary minus(-), unary plus(+), increment(++),decrement (--), logical not(!),
pointer indirection or dereference(*), address of(&) etc.
Syntax:
Returntype operator symbol (arg)
{
function body
}
The unary operators either prefix or postfix can be overloaded with non-static
member function taking no argument or non-member function taking one
argument. After overloading the operator, it can be applied to an object in the
same way as it is applied to the basic types.