PREV NEXT
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); } |
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:
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; } 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 } |
Let us have a look at the example to better understand the concept of function overloading:
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 30 31 32 33 34 35 36 37 38 39 40 41 |
#include <iostream> using namespace std; class Multiplication { public: int mul(int a,int b) { return a*b; } int mul(int a,int b, int c) { return a*b*c; } double mul(double a,double b) { return a*b; } }; int main(void) { Multiplication obj; cout<<obj.mul(2, 5)<<endl; cout<<obj.mul(7, 3, 1)<<endl; cout<<obj.mul(4.4, 10.8); return 0; } |