Function overloading is a mechanism for declaring multiple functions with the same name but different signatures (number or type of parameters).
Default values for parameters can be specified in the function declaration. Subtlety: default values are only considered during the compilation of the call, and are supplied by the compiler based on the visible signature.
In classes, you often encounter a situation:
class Printer { void print(int n, char c = '*') { /* ... */ } void print(const std::string& s) { /* ... */ } }; Printer p; p.print(5); // calls print(int n, char c = '*'), c = '*' p.print("Hi"); // calls print(const std::string&)
Subtleties:
void foo(int x, int y = 10); void foo(int x); foo(1); // Error: unclear which function to call
Where is the only place allowed to specify a default value for a class member function?
Answer: The default value for a class method is allowed to be specified in the method declaration within the class (or in the first declaration outside the class), but it is not allowed to specify it both in the class and in the implementation. Otherwise, a redefinition error will occur.
class X { void func(int x = 5); // Allowed here }; void X::func(int x) { /* ... */ } // But not here!
Story 1
In banking software, there was a compilation failure: some overloaded functions with different default values interfered with the unambiguous choice of the required one, calls were ambiguous at compile time — the result was an inability to build the release until manual corrections were made.
Story 2
In the team, there was a common style where all default values were moved to the implementation instead of the class header, however, for some class methods this caused a mismatch between interface and implementation — different TU saw different function parameters, leading to strange compilation and run-time bugs.
Story 3
When extending a public library, an overload of a function with the same parameters but different default values was mistakenly added. The compiler began to report ambiguity in API calls, and users faced outdated calls and broken binary compatibility.