Function overload

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The basics

    /

  4. Function overload

What is function overload?

Function overload is a fairly simple concept, yet very convenient. Function overload is a feature of C++, so it does not exist in C. When I code in C, function overloading is the thing I miss the most from C++. So, what is function overload? Function overload is when we define many functions with the same name, but that take different arguments. When we call an overloaded function, the correct version is called depending on the arguments given to it. Let us consider those 3 functions:

1
2
3
4
5
6
7
8
9
void function(){ std::cout << “no argument” << std::endl; } void function(int arg){ std::cout << arg << std::endl; } void function(int arg, int arg2){ std::cout << arg * arg2 << std::endl; }

The following line:

function(5);

Would cause the second version of function to be called. Therefore, the result would be that the number 5, followed by a new line, would be written to the console.

This instruction:

function();

Would call the first version of function. The text “no argument” would be outputted into the console, followed by a new line.

And then:

function(10, 2);

Would cause the third version to be executed. The number 20 (10*2), followed by a new line, would be written in the console.

Why is it useful?

If we wanted to, for example, create functions to print the content of a variable to the console, we would have, in C, to name the functions differently depending on the type of variable they take in argument, like printFloat, printUnsigned or printInt.

So, without function overloading, to define functions that print values of type int and double to the console, we have to write something like:

1
2
3
4
5
6
7
8
void printDouble(double var) { std::cout << var << std::endl; } void printInt(int var) { std::cout << var << std::endl; }

With function overloading, we can simply write:

1
2
3
4
5
6
7
8
void print(double var) { std::cout << var << std::endl; } void print(int var) { std::cout << var << std::endl; }

The appropriate version of print will then be called depending on the type of the argument given to it.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> void print(double var) { std::cout << "double: " << var << std::endl; } void print(int var) { std::cout << "int: " << var << std::endl; } int main() { print(100); print(123.456); return 0; }