Function Overloading and Operator Overloading - Leo Tutorials

Overloading : Overloading refers to take the use of the same thing for different purposes. It simply means 'one name,multiple forms'.

  Function Overloading : We can use the same function name to create functions that perform a variety of different tasks. This is known as function overloading. Using the concept of function overloading. We can design a family of functions with one function name but with different arguments lists. The function would perform the different operations depending on the arguments lists in the function call. For example, an overloaded add() function handles different types of data as shown below :

int add(int a, int b);
int add(int a, int b,int c);
double add(double x, double q);
double add(int p, double q);
double add(double p, int q);
//Function calls
cout<<add(5, 10, 15);
cout<<add(0.75, 5);

The function selection involves the following steps :

  1. The compiler first tries to find exact match in which the types of actual arguments are the same, and use that function.
  2. If an exact match is not found, the compiler uses the integral promotion to the actual arguments, such as,
char to int
float to double
to find the match.

       3.When either of them fails, the compiler tries to use the built-in-conversions (the implicit assignment conversions) to the actual arguments and the uses the function whose match is unique.

      4.If all the steps fail, then the compiler will try the user-defined conversions in combination with integral promotions and built-in-conversions to find a unique match.
     Operator Overloading : Operator overloading provides a flexible option for the creating of new definitions for most of the c++ operators. Operator overloading is accomplished by means of special kind of function. This function is called operator function.The general form of an operator function is 

               return type class name :: operator op(arguments list)
                 function body

         where return type is the type of value returned by the specified operation and op is the operator being overloaded. The op is preceded by the keyword operator. Operator op is the function name.
          The process of operator overloading involves the following steps :

  • Create a class that define the data type that is to be used in the overloading operation,
  • Declare the operator function, operator op() in the public part of the class. It may be either a member functions or a friend function.
  • Define the operator function to implement the required operation.

Post a comment