Sunday, February 13, 2011

Function Overloading:


Function Overloading:
Function Overloading refers the use of same function name to perform a variety of different tasks. In function overloading concept, a number of functions are made with a one function name but with different argument lists (may be different number of arguments or different type of arguments). The function would perform different operations depending on the argument list in the function call. The correct function is determined by either number of arguments and type of the arguments.
 Examples:
a) Different number of arguments
#include<iostream.h>
#include<conio.h>
int add(int, int);
int add(int,int,int);
void main()
 {
 int r1,r2;
 clrscr();
 r1=add(10,30); // function add() is called which has only two arguments
 r2=add(20,30,40); //function add() is called which has three arguments
 cout<<"Result1="<<r1<<endl<<"Result2="<<r2;
 getch();
 }

int add(int a,int b)
 { return(a+b); }

 int add(int a, int b, int c)
   {   return(a+b+c);   }

In this example, there are two user-defined function named add() but they have been used for different purposes. One has been used to add two integer number and other is to add three integer numbers. The exact function is called according to number of arguments passed while calling the function. In first call (i.e. add(10,30)), only two arguments have been passed. Thus first prototype (i.e. int add(int, int)) is used which adds two numbers. In second function call, three numbers have been passed. This it uses second function prototypes.

b) Different Kind of arguments:
#include<iostream.h>
#include<conio.h>
int absolute(int x);
long absolute(long y);
void main()
 {
 int num,r1;
 long lnum,r2;
 clrscr();
 cout<<"Enter an integer -ve or +ve"<<endl;
 cin>>num;
 cout<<"Enter a long number -ve or +ve"<<endl;
 cin>>lnum;
 r1=absolute(num);
 r2=absolute(lnum);
 cout<<endl<<"Absolte Value for int="<<r1<<endl<<"Absolute Value for long="<<r2;
 getch();
 }

int absolute(int a)
 {  cout<<"I am from funtion 1"<<endl;
   return(a>0?a:a*-1); }

long absolute(long a)
   {  cout<<endl<<"I am from function 2"<<endl;
   return(a>0?a:a*-1);   }

Output:
   Enter an integer -ve or +ve     -34
   Enter a long number -ve or +ve   -120000
          I  am from funtion 1
          I am from function 2
         Absolte Value for int=34
         Absolute Value for long=120000

In this example, same function absolute() is used to calculate absolute value of both integer and long integer. The appropriate function is called according to type of arguments passed to it. If integer is passed as actual argument, then first function absolute is used which calculates absolute value of integer. Similarly, if long number is passed, another absolute function is called which calculates absolute value of long integer. This is illustrated as output.

2 comments: