Function overloading
Function overloading:-
Basic definition of function overloading
Function overloading is a feature of C++ that allows us to create
multiple functions with the same name, so long as they have different
parameters, for example the parameters list of a function myfuncn(int a, float b)
is (int, float)
which is
different from the function myfuncn(float a, int b)
parameter
list (float,
int)
. Function overloading is a compile-time polymorphism.
Using the concept of function
overloading. We can design a family of functions with one function name but
with different argument lists. The function would perform different operation
depending on the argument list in the function call. The correct function to be
invoked is determined by checking the number and type of the argument but not
on the function type. For example overloading sum() function that handles
different type of data as shown below:
// Declarations
Int add(int a, int b); // prototype 1
// Function calls
Cout<<add(5,10); // uses prototype 1
Cout<<add(5, 10, 15); // uses prototype 2
Cout<<add(12.5, 7.5); // uses prototype 3
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 be unique.
The function selection involves the following steps:
1.
The compiler first tries to find an 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 complier
uses the integeral promotions to the
actual arguments, such as,
Char to int
Float to double
#include<iostream.h>
#include<conio.h>
class
sum
{
public:
int
add(int a, int b)
{
return
a+b;
}
int
add(int a, int b, int c)
{
return
a+b+c;
}
int
add(double x, double y)
{
return
x+y;
}
};
void
main()
{
clrscr();
sum
s;
cout<<s.add(5,
10)<<endl;
cout<<s.add(5,
10, 15)<<endl;
cout<<s.add(12.5,
5.5);
getch();
|