Function overloading in C++

Two different functions may have the same name. This can be done if they have a different number of arguments. Such overloading is considered good practice.

An example of the add overload is another add function, but, for example, with three parameters.

double add(double a, double b, double c) { return a + b + c; }

You can overload a function with the same number of arguments - if the arguments have different types. This is considered bad practice.

Overloading by the type of the return value cannot be done.

#include <iostream> using namespace std; bool test(bool x) { return x; } bool test(double x) { return x > 0; } int main() { // 1 if (test(true)) { cout << "true passes the test" << endl; } // 2 if (test(3.2)) { cout << "3.2 passes the test" << endl; } // 3 if (test(3)) { cout << "3 passes the test" << endl; } return 0; }

1 and 2 can exist together just fine. But as soon as you want to check an integer - you will get an error.

overload.cpp: In function 'int main()': overload.cpp:31:17: error: call of overloaded 'test(int)' is ambiguous 31 | if (test(3)) | ~~~~^~~ overload.cpp:31:17: note: there are 2 candidates overload.cpp:4:6: note: candidate 1: 'bool test(bool)' 4 | bool test(bool x) | ^~~~ overload.cpp:9:6: note: candidate 2: 'bool test(double)' 9 | bool test(double x) | ^~~~

The code on this page was run with g++ 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Andrei Olegovich