+ 3
Can anyone please make the concept of operator overloading clear?
3 Réponses
+ 12
Overloading is simply, " having multiple definitions "
When we say " Operator Overloading ", we mean to say that we are adding our own custom definition to an inbuilt operator, to perform specific tasks at times when needed in our program, apart from it's default definition.
Example : the " + " operator can be overloaded to multiply (or) divide (or) subtract (or) increment (or) decrement (or) whatever you want it to do, apart from just adding operands.
In a nutshell, you can use an operator just like a function, to perform a specific task, whenever it's called.
Ex :
Consider two functions subtract(), divide():
subtract ( a , b ) { return a - b ; }
divide ( a , b ) { return a / b ; }
the above two functions can be substituted by operators if overloaded.
operator + ( a , b ){ return a - b ; }
operator * ( a , b ){ return a / b ; }
now, x + y * z does the same job as
subtract ( x , divide ( y , z ) )
so, operator overloading helps us use operators as functions.
+ 3
making the operator behave as per the context
for eg. let's take + operator... + can be used to add two numbers, two decimals, two complex numbers, two strings etc... as human we know how to treat + based on the type of operands, if we provide that intelligence to a program that would be cool, we can do that by operator overloading, which means giving different behaviours for the same operator based on the operands
- 7
Hi I am pradeep