Function Overloading in C++

What is Function Overloading in C++?

Explanation

Function Overloading is a method to define multiple functions with the same name. But different tasks are performed based on the number, type of arguments contained in that function.

Example :


#include <iostream.h>
int add(int, int);
double add( double , double );
int add(int , int , int );
int main()
{
cout << "Addition of 2 integers::"
<cout << "Addition of 2 double integers::"
<< add (12.5, 13.2) << '\n';
cout << "Addition of 3 integers::"
<< add (10, 20) << '\n';
return 0;
}
int add (int a, int b)
{
return a+b;
}
double add ( double x, double y)
{
return x+y;
}
int add ( int u, int v, int w )
{
return u+v+w;
}

Result :

Addition of 2 integers::13
Addition of 2 double integers::25.7
Addition of 3 integers::30

In the above example there are multiple "add" functions, but with different arguments, types. So based on the type and arguments the respective function is called.

C++ Tutorial


Ask Questions

Ask Question