• Register

C++ enables some functions of the same name to be defined. The functions of the same name must have different signatures. This is called function overloading. The compiler selects the correct function to call by examining the number, types and order of the arguments in the call. We use function overloading to create functions of the same name that can perform similar tasks, but on different data types. For example, many functions in the math library are overloaded for different numeric types -- the C++ standard requires float, double and long double overloaded versions of the math library functions.

Two or more functions may have the same name provided that

Two or more functions may have the same name provided that they have different signatures.
 

Example

#include <iostream>
using namespace std;

int square( int x )
{
cout << "square of integer " << x << " is ";
return x * x;
}
double square( double y )
{
cout << "square of double " << y << " is ";
return y * y;
}

int main()
{
cout << square( 7 );
cout << endl;
cout << square( 7.5 );
cout << endl;
}

Output

square of integer 7 is 49
square of double 7.5 is 56.25

How the compiler differentiates among overloaded functions?

Overloaded functions are distinguished by their signatures. A signature is a combination of a function’s name and its parameter types (in order). The compiler encodes each function identifier with the type of its parameters (sometimes referred to as name mangling or name decoration) to enable type-safe linkage. Type-safe linkage ensures that the proper overloaded function is called and that the types of the arguments conform to the types of the parameters.

100 points
7 4