Function overloading is also called function polymorphism. Poly means many, and morph means form: A polymorphic function is many-formed.
Often you will find that you need two or more functions that do essentially the same thing, but to different data types. For example, you might need several versions of function larger(), for finding the larger of two variables of any of the basic numeric data types. Ideally, of course, all of these functions would have the same name, larger(). The alternative would be to define a function largerint() for variables of type int, and a function largerfloat() for variables of type float, and so on – which is clumsy and laborious. This is a case for function overloading.
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 that performs a variety of different tasks. This is known as function overloading.
Using the concept of function overloading; we can assign 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 called 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.
The Signature of a Function
The combination of the name of a function, together with its parameter types defines a unique characteristic called the function signature. The function signature serves to differentiate one function from another – each function in your program must have a unique function signature. It comes into play whenever you call a function in your program.
From the function prototypes or the function definitions, the compiler creates a function signature for each function in your program file. When you write a statement that includes a function call, the compiler uses the call to create a function signature, and then compares it with the set of function signatures which are available in your function prototypes and/or definitions. If it finds a match, then it is established which function you called. If it doesn’t find a match, then it will check to see whether any conversions on the arguments will produce a match.
Program 5:
#include<iostream.h>
#include<conio.h>
int add(int,int); // prototypes
double add(double,double);
double add(int,int,double);
void main()
{
int x;
double y,z;
x=add(10,20);
y=add(3.5,4.5);
z=add(10,30,5.5);
cout << "Ans is :" << "x = " << x << " y = " << y << " z = " << z;
getch();
}
int add(int a, int b)
{
return (a+b);
}
double add(double a, double b)
{
return (a+b);
}
double add(int a, int b, double c)
{
return (a+b+c);
}
Made By: Chaudhary Amit V.
Comments
Post a Comment