C++ Function Overloading

In C++, the functions are said to be overloaded if two or more functions share the same name differs in their parameter declarations and the process is referred to as function overloading.

An overloaded function appears to perform different activities depending on the kind of data sent to it.

When an overloaded method is invoked, C++ uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method.

When C++ encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.

 

The two ways to achieve function overloading are:

Different Numbers of Arguments

It would be far more convenient to use the same name for all three functions, even though they each have different arguments.

Here is a simple example that illustrates method overloading:

//function overloading example
#include<iostream>
using namespace std;

void print()
{
    cout<<"No parameters" << endl;
}

// Overload print for one integer parameter.
void print(int a)
{
    cout<<"a: " << a <<endl;
}

// Overload print for two integer parameters.
void print(int a, int b)
{
    cout<<"a and b: " << a << " " << b <<endl;
}

int main()
{
    print();
    print(4);
    print(5,9);
}

The output of the program is:

No parameters 
a: 4 
a and b: 5 9

The program contains three functions with the same name. Compiler uses the function signature—the number of arguments, and their data types—to distinguish one function from another.

Figure below shows the process how different functions are called.

function overloading

Figure: Function overloading 

 

 Different Types of Arguments

In above example, we created several functions with the same name but different numbers of arguments. The compiler can also distinguish between overloaded functions with the same number of arguments, provided their type is different.

Here’s a example program that uses an overloaded function to sum different input numbers.

//function overloading example
#include<iostream>
using namespace std;

void add(int a,int b)
{
    cout<<"Sum: " <<a<< " + " <<b<< " = " << (a+b) << endl;
}

// Overload add for integer and float parameters.
void add(int a,float b)
{
    cout<<"Sum: " <<a<< " + " <<b<< " = " << (a+b) << endl;
}

// Overload add for two floating number parameters.
void print(float a, float b)
{
    cout<<"Sum: " <<a<< " + " <<b<< " = " << (a+b) << endl;
}

int main()
{
    print(4,6);
    print(4,6.1);
    print(4.6,9.2);
}

The output of the program is:

Sum : 4 + 6 = 10 
Sum : 4 + 6.1 = 10.1 
Sum : 4.6 + 9.2 = 13.8 
C++ Functions
C++ Inline Function & Default Arguments