Function Overloading in C++ Tutorial

“There are moments when mental overload can render words impossible” Nicholas Sparks

Function overloading means creating multiple functions all with the same name but either the parameter’s data-type or the number of parameters for each function should be different than the other.

Notes:

  • The return data-type of each function may or may not be the
    same.

  • The function’s arguments list is known as
    function-signature.

We use function overloading to design a family of functions that basically do the same thing but with different arguments list.

This is because sometimes we want to do the same task but on different data-types, like for example we want to multiply two values together and return the result no-matter if it’s a float type or integer type.

In such case we could use two functions with different names each devoted to one data-type. But with the help of function overloading we can create two functions with the same name but one accepts arguments of type float and the other accepts arguments of type int.

Note: based on the type of arguments we put to an overloaded function, the computer will figure out which function is the target one that its instructions should be run.

Example:

#include <iostream>
using namespace std;
int multiply(int i, int b);
double multiply (double a, double b);
int main() {
cout<<multiply(3,5)<<endl;
cout<<multiply(2.3, 4.4)<<endl;
return 0;
}
int multiply(int i , int b){
cout<< "Calling from integer-type function"<<endl;
return i*b;
}
double multiply (double a, double b){
cout<< "Calling from double-type function"<<endl;
return a*b;
}

Output:

Calling from integer-type function

15

Calling from double-type function

10.12

In this example as you can see we have two functions both named multiply() but one of them takes arguments of type int and the other takes arguments of type double, float.

Within the body of the main() function, we first called the multiply() function with the value of type int and so the computer realized we want to call the function that accepts only integer values.

This is why we first got the message Calling from integer-type function.

After the first call to the multiply() function, we again called it again but this time with values of type double. And because we used double data-type values, it is the function that accepts arguments of type double that will be called and that’s why we got the message Calling from double-type function after calling the multiply() function the second time.