Function overloading in cpp

Function overloading in cpp is the object oriented programming feature.

In this tutorial we will see function overloading in cpp, program for function overloading.

What is function overloading

Writing the same function name with different arguments or different argument list is known as function overloading.

Function overloading definition A set of function which having same name but performs different tasks by passing different parameters.

Why we use function overloading

If we want to perform same task but with different type of different number of argument then we overload function.

Function overloading example

Suppose if we want to add integer first then we want to add 3 integer again then we use same name addition function but having different number of integer arguments.

Function overloading

Function overloading implemented by following cases :

Case 1  : Number of arguments accepted by function is different.

Example :

void add(void);

void add(int,int);

Case 2 : If the number of arguments accepted by function is same then function calling is distinguished by their data types of arguments.

Example :

void add(int,int);

void add(float,float);

Program for function overloading

123456789101112131415161718192021222324252627282930313233#include <iostream>using namespace std;void square(double);void square(int);int main(){    square(10.5);square(10);    return 0;}void square(double s){float val= s*s;cout<<“square of float numbers= “<<val;}void square(int s){int res=s*s;cout<<“\nsquare of int numbers= “<<res;}

Output :

program for function overloading
program for function overloading

Explanation :

1. First we write a header files in program.

2. Next we declare function that we want to overload

=>void square(float);

void square(int);

3. Write a main function

4. Now call the function that we overloaded by passing value to function.

5. We first call function square(10.0);

6. Control transferred to function and function executed.

void square(float s)  => s = 10.0

float val= s*s; => val = 100.0

cout<<“square of float numbers”<<val;

=> square of float numbers 100.0

7. Then again control transferred to main.

8. Now we call second function by passing integer value

=> square(10);

9. Control transferred to function and function executed

void square(int s) => s = 10

int res=s*s; => res =100

cout<<“square of int numbers”<<res;

=> square of int numbers 100

10. End with the program.