C++ Notes to Self: Function Overloading

C/C++
‘With function overloading, multiple functions can have the same name with different parameters.’ [w3schools.com]
Author

Dennis Chua

Published

February 25, 2017


In C++ function overloading, two or more functions can have similar names but different parameter type signature.

In case the function parameter accepts a pointer or a reference, adding the const modifier also differentiates the parameter type signature of the overloaded functions. Any passed parameter that is of type const will match the function with the const parameter type signature. A few more points on C++ function overloading:

Function overloading is an example of static polymorphism. Internally, the C++ compiler resorts to name mangling to give overloaded functions unique names. Because each compiler uses different algorithms to implement name mangling, the lack of a standard prevents C++ functions to be called from code written in C or any other language.

extern "C" is a compiler directive that is applied to the declaration and the definition of global functions and variables. It suppresses name mangling. In a set of overloaded functions, it can only be applied to one function, allowing that to be called from C or any other language. To inspect the mangled function names, we rely on a map file that the linker generates.

#include <iostream>

using namespace std;

int myAdd(int x, int y);
float myAdd(float x, float y);

int main(int argc, char **argv) {

    cout << myAdd(111,222) << endl;
    cout << myAdd(1.2f, 2.1f) << endl;

    return 0;
}

int myAdd(int x, int y) {
    return x + y;
}

float myAdd(float x, float y) {
    return x + y;
}