Chapter 4 :Function overloading & operator oveloading



Overloading refers to the use of the same thing for different purposes. c++ also permits overloading of functions. This means that we can use the same function name to create functions than perform a variety of different tasks. This is known as functions polymorphism in OOP. Using the concept of function overloading, we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type. A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. A best match must be unique.
Operator Overloading :
To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function called operator functionThe general form of operator function is :
return type classname :: operator op (arg-list)
{

Function body //task defined
}
Where return type is the type of value returned by the specified operation and op is he operator being overloaded. The op is preceded by the keyword operatoroperator op is the function name.
The process of overloading involves the following steps :
1.
First, create a class that defines the data type that is to be used in the overloading operation.

2.
Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function.

3.
Define the operator function to implement the required operations.

Let us consider the unary minus operator. A minus operator, when used as a unary, takes just one operand. We know that this operator changes the sign of an operand when applied to basic data item. we will see here how to overload this operator so that it can be applied to an object should change the sign of each of its data items.
We have just seen how to overload a unary operator. The same mechanism can be used to overload a binary operator.