Operator Overloading
Operator Overloading
The capability to relate the existing operator with a member function and use the resulting operator
with objects of its class as its operands is called operator overloading. It is one of the most valuable
concepts introduced by c++ language. It is a type of polymorphism. Polymorphism permits to write of
multiple definitions for functions and operators. C++ has the number of standard data types like int,
float, char etc. The operators +,-,*, and = are used to carry out operations with these data types.
Operator overloading helps the programmer to use these operators with the objects of classes. The
outcome of operator overloading is that objects can be used in a natural manner as the variables of
basic data types.
Operator overloading provides a flexible option for the creation of new definitions for most
of the C++ operators. We can overload all the C++ operators except the following:
operator functions are declared in. the class using prototypes as follows:-
vector operator + (vector); /./ vector addition
vector operator-( ); //unary minus
friend vector operator + (vuelor, vector); // vector add
friend vector operator -(vector); // unary minus
vector operator - ( vector &a); // substraction
int operator = =(vector); //comparision
friend int operator = =(vector ,vrctor); // comparision
vector is a data type of class and may represent both magnitude and direction or a series
of points called elements.
The process of overloading involves the following steps:-
1. Create a class that defines the data type that is used in the overloading operation.
2. Declare the operator function operator op() in the public part of the class
3. It may be either a member function or friend function.
4. Define the operator function to implement the required operations.
Overloaded operator functions can be invoked by expressions such as
op x or x op;
for unary operators and
x op y
for binary opearators.
operator op(x);
for unary operator using friend function
operator op(x,y);
for binary operator usinf friend function.
Overloading an operator does not change its basic meaning. For example assume the +
operator can be overloaded to subtract two objects. But the code becomes unreachable.
class integer
{
intx, y;
public:
int operator + ( ) ;
}
int integer: : operator + ( )
{
return (x-y) ;
}
Unary operators, overloaded by means of a member function, take no explicit argument and
return no explicit values. But, those overloaded by means of a friend function take one
reference argument (the object of the relevant class).
Binary operators overloaded through a member function take one explicit argument and those
which are overloaded through a friend function take two explicit arguments.
Table 1
Operator to Arguments passed to the Arguments passed to the Friend
Overload Member Function Function
Unary Operator No 1
Binary Operator 1 2