C++ Function Overloading and Default Arguments

In C++ many functions can have the same name if their parameters are different. This is function overloading. The compiler chooses the right one from the arguments.

#include <iostream>
#include <string>

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
std::string add(const std::string& a, const std::string& b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }

int main() {
    std::cout << add(2, 3) << '\n';
    std::cout << add(2.5, 3.5) << '\n';
    std::cout << add(std::string("C++"), std::string("23")) << '\n';
    std::cout << add(1, 2, 3) << '\n';
}
Output

5
6
C++23
6

A different return type alone is not enough:

int value() { return 1; }
double value() { return 1.0; }

int main() { }
Output

Same.cpp:2:8: error: ambiguating new declaration of 'double value()'
2 | double value() { return 1.0; }
| ^~~~~
Same.cpp:1:5: note: old declaration 'int value()'
1 | int value() { return 1; }
| ^~~~~

Default arguments

#include <iostream>
#include <string>

void print_line(const std::string& text, char border = '*', int times = 1) {
    for (int i = 0; i < times; i++) {
        std::cout << border << ' ' << text << ' ' << border << '\n';
    }
}

int main() {
    print_line("Hello");
    print_line("Hello", '#');
    print_line("Hello", '-', 2);
}
Output

* Hello *
# Hello #
– Hello –
– Hello –

Default values must be the last parameters. They are written in the declaration, not again in the definition.

Ambiguous calls

When two overloads fit equally well, the compiler can not choose and gives an error:

#include <iostream>

void show(long x) { std::cout << "long\n"; }
void show(double x) { std::cout << "double\n"; }

int main() {
    show(5);              // int can become long or double: which one?
}
Output

Ambiguous.cpp: In function 'void show(long int)':
Ambiguous.cpp:3:16: warning: unused parameter 'x' [-Wunused-parameter]
3 | void show(long x) { std::cout << "long\n"; }
| ~~~~~^
Ambiguous.cpp: In function 'void show(double)':
Ambiguous.cpp:4:18: warning: unused parameter 'x' [-Wunused-parameter]
4 | void show(double x) { std::cout << "double\n"; }
| ~~~~~~~^
Ambiguous.cpp: In function 'int main()':
Ambiguous.cpp:7:9: error: call of overloaded 'show(int)' is ambiguous
7 | show(5); // int can become long or double: which one?
| ~~~~^~~
• there are 2 candidates
• candidate 1: 'void show(long int)'
Ambiguous.cpp:3:6:
3 | void show(long x) { std::cout << "long\n"; }
| ^~~~
• candidate 2: 'void show(double)'
Ambiguous.cpp:4:6:
4 | void show(double x) { std::cout << "double\n"; }
| ^~~~

Note: Overloading is good when the functions do the same job on different types. If they do different jobs, use different names. Next: C++ References.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.