CS300: Object Oriented Analysis and Design
Polymorphism
(Using C++)
Operator overloading
Compiler sees an expression consisting of an argument followed by an operator followed by an argument, it simply calls a function.
An operator is simply a function call with a different syntax.
There must be a previously declared function to match that operator
Operator overloading is just “syntactic sugar,” which means it is simply another way for you to make a function call.
Is the knowledge about operator wrong ?
1 << 4;
1.414 << 1;
won’t suddenly change its meaning
won’t suddenly start working.
Operator overloading
We are already overloading
int i;
cin >> i;
float f;
cin >> f;
char c;
cin >> c;
char buf[100];
cin >> buf;
Operator overloading
Creating a Member operator function
Ret-type classname::operator#(arg-list){
//operations
}
// Overload + for loc.
loc loc::operator+(loc op2)
Demonstration
Can we overload all operators
+ | - | * | / | % | ^ |
& | | | ~ | ! | , | = |
< | > | <= | >= | ++ | -- |
<< | >> | == | != | && | || |
+= | -= | /= | %= | ^= | &= |
|= | *= | <<= | >>= | [] | () |
-> | ->* | new | new [] | delete | delete [] |
:: | .* | . | ?: |
Parameter passing to operator function
Operator function
Global
Unary (1)
Binary (2)
Member
Unary (0)
Binary (1)
The number of arguments in the overloaded operator’s argument list depends on two factors
Restrictions
Overloading Unary Operator