Page 145 - DCAP404 _Object Oriented Programming
P. 145
Object-oriented Programming
Notes
Task Operator overloading is the ability to tell the compiler how to perform a certain
operation when its corresponding operator is used on one or more variables. Discuss.
Why would you do this? when the operator is a class member, the first object in the expression
must be of that particular type. It’s as if you were writing:
Complex a( 1, 2 );
Complex a( 2, 2 );
Complex c = a.operator=( b );
when it’s a global function, the implicit or user-defined conversion can allow the operator to act
even if the first operand is not exactly of the same type:
Complex c = 2+b; //if the integer 2 can be converted by the Complex
class, this expression is valid
By the way, the number of operands to a function is fixed; that is, a binary operator takes two
operands, a unary only one, and you can’t change it. The same is true for the precedence of
operators too; for example the multiplication operator is called before addition. There are some
operators that need the first operand to be assignable, such as : operator=, operator(), operator[]
and operator->, so their use is restricted just as member functions (non-static), they can’t be
overloaded globally. The operator=, operator& and operator, (sequencing) have already defined
meanings by default for all objects, but their meanings can be changed by overloading or erased
by making them private.
Another intuitive meaning of the “+” operator from the STL string class which is overloaded to
do concatenation:
string prefix(“de”);
string word(“composed”);
string composed = prefix+word;
Using “+” to concatenate is also allowed in Java, but note that this is not extensible to other
classes, and it’s not a user defined behavior. Almost all operators can be overloaded in C++:
+ - * / % ^ & |
~ ! , = < > <= >=
++ — << >> == != && ||
+= -= /= %= ^= & = |= *=
<<= >>= [ ] ( ) -> ->* new delete
The only operators that can’t be overloaded are the operators for scope resolution (::), member
selection (.), and member selection through a pointer to a function(.*). Overloading assumes you
specify a behavior for an operator that acts on a user defined type and it can’t be used just with
general pointers. The standard behavior of operators for built-in (primitive) types cannot be
changed by overloading, that is, you can’t overload operator+(int,int).
The logic (boolean) operators have by the default a short-circuiting way of acting in expressions
with multiple boolean operations. This means that the expression:
if(a && b && c)
138 LOVELY PROFESSIONAL UNIVERSITY