Page 143 - DCAP404 _Object Oriented Programming
P. 143
Object-oriented Programming
Notes should produce a single string
“COMPUTER”
This act of redefining the effect of an operator is called operator overloading. The original
meaning and action of the operator however remains as it is. Only an additional meaning is
added to it.
Function overloading allows different functions with different argument list having the same
name. Similarly an operator can be redefined to perform additional tasks.
Operator overloading is accomplished using a special function, which can be a member function
or friend function. The general syntax of operator overloading is:
<return_type> operator <operator_being_overloaded>(<argument list>);
Here, operator is the keyword and is preceded by the return_type of the operation.
To overload the addition operator (+) to concatenate two characters, the following declaration,
which could be either member or friend function, would be needed:
char * operator + (char *s2);
7.1 Defining Operator Overloading
In C++ the overloading principle applies not only to functions, but to operators too. That is, of
operators can be extended to work not just with built-in types but also classes. A programmer
can provide his or her own operator to a class by overloading the built-in operator to perform
some specific computation when the operator is used on objects of that class. Is operator
overloading really useful in real world implementations? It certainly can be, making it very
easy to write code that feels natural. On the other hand, operator overloading, like any advanced
C++ feature, makes the language more complicated. In addition, operators tend to have very
specific meaning, and most programmers don’t expect operators to do a lot of work, so
overloading operators can be abused to make code unreadable. But we won’t do that.
Did u know? What is the advantage of operator overloading?
By using operator overloading we can easily access the objects to perform any operations.
An Example of Operator Overloading
Complex a(1.2,1.3); //this class is used to represent complex numbers
Complex b(2.1,3); //notice the construction taking 2 parameters for the
real and imaginary part
Complex c = a+b; //for this to work the addition operator must be overloaded
The addition without having overloaded operator + could look like this:
Complex c = a.Add(b);
This piece of code is not as readable as the first example though—we’re dealing with numbers,
so doing addition should be natural. (In contrast to cases when programmers abuse this technique,
when the concept represented by the class is not related to the operator—ike using + and - to add
and remove elements from a data structure. In this cases operator overloading is a bad idea,
creating confusion.)
136 LOVELY PROFESSIONAL UNIVERSITY