C++ Function Overloading

WHAT IS FUNCTION OVERLOADING?

  • Overloading means the use of the same thing for different purposes. Function Overloading is a most important feature of C++ in which two or more functions can have the same name but different parameters or arguments for the different tasks.
  • It is known as function polymorphism in OOP. By using the concept of function overloading we can create a family of functions with one function name but with different parameters or arguments.
  • The function will perform different operations but on the basis of the argument list in the function call.

LET US HAVE A LOOK AT THE SYNTAX:

int test ( ) { }

int test ( int x) { }

int test ( int x, double y) { }

double test ( double a) { }

DIFFERENT WAYS TO OVERLOAD A FUNCTION

The function overloading can be done in two ways:

  • Having different types of argument
  • Changing number of arguments.

HAVING DIFFERENT TYPES OF ARGUMENTS:

In function overloading we can define two or more functions with same name and same number of arguments but the type of the argument is different.

LET US HAVE A LOOK AT THE EXAMPLE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iosteam>
 
using namesapce std;
 
int mul(int a,int b)
 
{
 
 cout<< a*b;
 
}
 
double mul(double a,double b)
 
{
 
 cout << a*b;
 
}
 
int main()
 
{
 
 mul (5,4);
 
 mul(2.3, 6.7);
 
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

NUMBER OF DIFFERENT ARGUMENTS:

In this type we define two functions with same names but with different number of arguments of the same type.

LET US HAVE A LOOK AT THE EXAMPLE:

 
 
 
 
 
 

C++

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
 
using namesapce std;
 
int mul (int a, int b)
 
{
 
 cout << a*b;
 
}
 
int mul(int a, int b, int c)
 
{
 
 cout << a*b*c;
 
}
 
int main()
 
{
 
mul (5,4);  // mul( ) with 2 parameter will be called
 
mul(3,2,9);  //mul( ) with 3 parameter will be called
 }
r

Output :

 

LET US HAVE A LOOK AT THE EXAMPLE TO BETTER UNDERSTAND THE CONCEPT OF FUNCTION OVERLOADING:

Output:

10
21
47.52