Summary: In this tutorial, we will learn the significance of function overloading in C++ with examples.

What is Function Overloading?

If more than one function has the same name but the parameters differs in numbers, types or order, the functions are called overloaded.

Example:

void add(int a, int b){
   //code to add two integers 
}

void add(float a, float b){
    //code to add two floating point numbers
}

Note: Return type is not considered as overloading criteria. Two functions with the same name can have different return type.

By overloading functions, we can write different implementations under the same name for different types or numbers of parameters, thus allowing us to call the function with different types of parameters.

It is the compiler that determines which function to call based on the parameters in the call statement. This is why function overloading is an example of compile-time polymorphism.

Let’s see an example implementing function overloading to understand its significance.

C++ Example: Function Overloading

#include <iostream>
using namespace std;
 
int maxx(int a, int b){
    return a>b ? a: b;
}
 
int maxx(int a, int b, int c){
    return a > b ? (a > c ? a: c) : (b > c ? b : c);
}
 
double maxx(double a, double b){
    return a > b ? a: b;
}
 
double maxx(double a, double b, double c){
    return a > b ? (a > c ? a: c) : (b > c ? b : c);
}
 
int main()
{
    cout << "Max of 2 & 3 is: " << maxx(2, 3) << endl;
    cout << "Max of 3.4 & 1.2 is: " <<  maxx(3.4, 1.2) << endl;
    cout << "Max of 2, 3, 5 is: " <<  maxx(2, 3, 5) << endl;
    cout << "Max of 3.4, 1.2 & 3.6 is: " <<  maxx(3.4, 1.2, 3.6) << endl;
 
    return 0;
}

Output:

Function Overloading in C++

In the above example, we have overloaded four maxx functions with different parameters.

The compiler maps each call statement in the main method to the correct maxx function during the compile-time based on the parameter.

Conclusion

Function overloading is defining multiple functions of same name but different parameters.

Function overloading is compile-time Polymorphism because binding of the call statement to the exact matching function is done during compile time only i.e. which version of the function should be called is decided during compile time.

It gives the power to use multiple data types and parameters under the same function name.

Leave a Reply