Functions overloading

In C++, it’s quite common to have several functions with same name, though they must have a different list of arguments. For instance, one can have the following three functions to compute the maximum of two or more values. Note that std::string is used to represent strings (i.e. text).

// Return the largest of x and y
double max(double x, double y) {
    if (x < y) {
        return x;
    }

    return y;
}

// Return the maximum number stored in V
double max(const std::vector<double>& V) {
    double result = V[0];

    for (double x : V) {
        if (x > result) {
            result = x;
        }
    }

    return result;
}

// Return the lexicographically largest word stored in V
std::string max(const std::vector<std::string>& V) {
   std::string result = V[0];

    for (std::string word : V) {
        if (word > result) { // lexicographical order is used
            result = word;
        }
    }

    return result;
}

It’s natural that all functions above have the same name because they all conceptually do the same task, i.e. compute the largest of two or more given values. However, the functions differ on the type and number of arguments they accept. The first function expects two doubles as arguments, while the second and third functions expect a vector of doubles and a vector of strings, respectively.

int main() {
    std::vector<std::string> words_list = {"Theoder", "Ebba", "Mark", "Anna", "Isak"};

    std::cout << max(words_list);
}

The function call max(words_list) calls the third function max given above because the actual argument words_list used in the function call has type std::vector<std::string> which is compatible with the type of the formal parameter of the third function.

Function overloading is used quite often in the C++-standard library. See, for instance, the function std::getline to read a line of text.