Default Arguments in C++
In this lesson: Give function parameters default values in C++ — rules, order and examples with output. In Hindi & English.
What are default arguments?
Default arguments let you give a parameter a value in advance, so the caller can leave it out. If they omit it, the default is used; if they pass a value, that wins. This makes some parameters effectively optional.
A working example
#include <iostream>
using namespace std;
void greet(string name, string msg = "Hello") {
cout << msg << ", " << name << "!\n";
}
int main() {
greet("Amit"); // uses default msg
greet("Riya", "Welcome"); // overrides default
return 0;
}Hello, Amit!
Welcome, Riya!
The trailing rule
Defaults must be on the rightmost parameters. Once one parameter has a default, all parameters to its right must have defaults too:
void f(int a, int b = 2, int c = 3); // OK // void g(int a = 1, int b); // ERROR: b has no default
This is because arguments fill in left to right — you cannot skip a middle one and supply a later one.
Where to put the default
If your function has a separate prototype, put the default there (not in the definition):
int power(int base, int exp = 2); // default in prototype
int power(int base, int exp) { // no default here
int r = 1;
for (int i = 0; i < exp; i++) r *= base;
return r;
}Putting the same default in both places is a compile error.
With overloading
Default arguments can overlap with overloading, but be careful — if a defaulted call could match two functions, the compiler reports an ambiguity. Prefer one approach or the other for a given set of calls.
Common mistakes
- Putting a default on a middle parameter but not the ones after it.
- Repeating the default in both the declaration and the definition.
- Creating an ambiguity between a defaulted function and an overload.
- Assuming you can skip an argument in the middle of a call — you cannot.
Write a function printLine(char symbol = '-', int length = 20) that prints a line of the given character. Call it with no arguments, one argument, and both, and observe the output.
Summary
- Default arguments give parameters fallback values, making them optional.
- A supplied value overrides the default; an omitted one uses it.
- Defaults must be on the trailing (rightmost) parameters.
- Put the default in the prototype, not repeated in the definition.
- Watch for ambiguity when mixing defaults with overloading.
Frequently Asked Questions
What are default arguments in C++?
How do default arguments work in C++?
void greet(string msg = "Hi"). Calling greet() uses "Hi", while greet("Hello") uses your value. The compiler fills in any missing trailing arguments with their defaults.