website logo

Function Overloading in c++

Function Overloading is a technique to use same function name for different purposes. means we can write same function name to perform different tasks . we also called this technique as a function polymorphism in object oriented programming.
one function name but different arguments using function overloading technique we can write group of function of same name but argument of each overloaded function will be different. whenever we call overloaded function that will be called depending on argument.


Example of overloaded function

int addition(int a , int b); /* function prototype 1 (argument in this overloaded function are (int , int)*/

int addition(int a , int b , int c); /* function prototype 2 (argument in this overloaded function are (int , int, int)*/

double addition(double x , double z); /* function prototype 3 (argument in this overloaded function are (double , double)*/

double addition(double y , int b); /* function prototype 4 (argument in this overloaded function are (double , int))*/

double addition(int a , double b); /* function prototype 5 (argument in this overloaded function are (int , double))*/


How to call overloaded functions

cout << addition(3,9); //argument in this function call are 3, 9 . both integer so call goes to function prototype 1

cout << addition(5, 10.2); //argument in this function call are 5, 10.2 .first one are integer and second one are double so call goes to function prototype 5

cout << addition(5.5, 6.7); //argument in this function call are 5.5 and 6.7 .both are doubel so call goes to function prototype 3

cout << addition(5.3, 7); //argument in this function call are 5.3, 7 .first one are double and second one are integer so call goes to function prototype 4

cout << addition(5, 7, 19); //argument in this function call are 5, 7, 19 . all integer so call goes to function prototype 2

Function return type is not play important role in function overloading . function overloading totally depend on functions argument.

In function overloading compiler first tries to find exact match if not find exact match then call appropriate function for execution.
compiler use integral promotions to the actual argument if exact function prototype not found for example
compiler promote char to int and float to double.


Example of Function overloading

Find area of rectangle using function overloading

#include<iostrem>
// prototype declaration
int area(int,int);
double area(double,int);
int main()
{
cout << area(4,6) <<"\n";
cout << area(4.5,7) <<"\n";
return 0;
}
// Function Definitions
int area(int a,int b){
return(a*b);
}
double area(double x ,int y);{
return(x*y);
}

in the above program first area(int,int) call and then area(double,int)will be call.
program print result
24
31.5