Function overloading with Example and Program

Explain Function overloading with Example and Program



Function overloading:- 


Function overloading can be defined as define a set of functions having same name and different signatures. The same function name will be used with different number of parameters and parameters of different type. We can use the same function name to create function that performs a variety of different tasks. This is known as function overloading (function polymorphism) in OOP. The function can perform different operations depending on the argument list in the function call. At the time of calling correct function to be invoked is determinates by checking the number and type of the argument but not on the function return type.  
For ex an overloaded add( ) function handles different types of data as follows.

            void    max (int a, float b); // prototype 1
            void    max(int a, int b, int c); // prototype 2
            void     max (double x, double y);// prototype 3
            void     max(float p, int q); // prototype 4
The following function calls can be given in the program
            x= add (0.75,5);//uses prototype 4
            y= add (5,10,15);// uses prototype 2
            z= add (5,10.5);//uses prototype 1
            p= add (12.5,17.5); // uses prototype 3

Rules that govern the usage of function over loading:
1.    The compiler first tries to find an exact match, in which the type of actual parameters are the same and use that function.
2.    If an exact match is not found then the compiler converts the arguments as follows.
i.    char to int
ii.    float to double
iii.    int to float or double
iv.    All these conversions take place to find a match.
3.    Some times compiler generate ambiguity errors because the compiler may not be able to decide what signature function should be called. If the conversion is possible to have multiple matches then the compiler generates an error message. Suppose we use the following 2 functions.
            long square (long n);
            double square (double x);
    A function call such as square (100) will cause an error because ‘int’ argument 100 can be converted to either long or double. The following is an ex: program that shows the usage of function overloading

#include <iostream.h>
#include <iomanip.h>
void main()
{     float area (int r);     // over loaded function
int area (int l, int b);    //over loaded function.
float a;
int a1,l,b,r , a1 ;
cout <<“enter the radius of the circle “<<endl;
cin>>r;
a=area(r);
cout << “ area of the circle is “<<a<,endl;
cout <<“enter the length and breadth of the rectangle”;
cin>>l>> b;
a1= area(l,b);

cout<<“area of the rectangle is “<<a1<endl;

float area (int r)
{    return (3.141*r*r);    }
int area (int l, int b)
{    return (l*b);       
}   
     


Labels: