
Operator Overloading
Operator overloading is one of the most exciting features of object oriented programming. It is an important technique that has enhanced the power of extensibility of C++. It can transform complex, obscure program listings into intuitively obvious ones.
For Example,
a3 . add ( a1, a2 ) ;
or
a3 = a1 . add ( a2 ) ;
can be changed to the much more readable
a3 = a1 + a2 ;
C++ tries to make the user-defined data types behave in much the same way as the built-in types. For instance, C++ permits us to add two variables of user-defined data types with the same syntax that is applied to the basic types.
When the operator is used in the context of ordinary variables, ordinary meaning is assigned. When an operator is assigned to an object of the class in which the operator has been overloaded the control goes to the overloading function ( calling it implicitly ) and a new meaning is given.
For Example,
If k is an integer, then ++k has the normal meaning of incrementing k by 1. Now suppose we have an object pt1 of class Point, which has two attributes x and y coordinates. The increment operator is overloaded and has to be suitably defined a method in the class Point. Most natural possible definition is to increment the x and y coordinates by 1.
An overloaded operator function is defined in the same way as a normal function except that its name consists of the keyword operator followed by one of the predefined permissible C++ operators.
For Example,
class string
{
public :
string & operator = ( const string & ) ;
// . . .
} ;
int main ( )
{
string s1 ( "helo world" ) ;
string s2;
s2 = s1 ;
return 0 ;
}
The statement
s2 = s1 ;
invokes the function string : : operator = ( ). Here s2 becomes the invoking instance and s1 becomes the explicit argument. The same result can be obtained if the assignment statement is written using functional notation:
s2 . operator = ( s1 ) ;
It should return a reference to a string object to allow the function cascading, such as
string s2, s3 ;
s1 = s2 = s3 ;
which is equivalent to:
s1 . operator = ( s2 . operator = ( s3 ) ) ;
Operator functions must be either member functions ( non static ) or friend functions. A basic difference between them is that a friend function will have only one argument for unary operators and two for binary operators, while a member function has no arguments for unary operators and only one for binary operators. This is because the object used to invoke the member function is passed implicitly and therefore is available for the member function. This is not the case with friend functions.