🧩 What are Default Parameters?
A default parameter in C++ means giving a default value to a function’s parameter.
If the caller doesn’t provide an argument for that parameter, the default value is used automatically.
🧠 Syntax:
void functionName(int a, int b = 10) {
cout << "a: " << a << ", b: " << b << endl;
}
👉 Here, b has a default value of 10.
✅ Example:
#include <iostream>
using namespace std;
void greet(string name = "Guest") {
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet("Amit"); // passes a custom argument
greet(); // uses default parameter
return 0;
}
🖨️ Output:
Hello, Amit!
Hello, Guest!
⚙️ Example with Multiple Parameters:
#include <iostream>
using namespace std;
void display(int a, int b = 20, int c = 30) {
cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
}
int main() {
display(10); // uses default for b and c
display(10, 40); // uses default for c
display(10, 40, 50);// uses all given values
return 0;
}
🖨️ Output:
a = 10, b = 20, c = 30
a = 10, b = 40, c = 30
a = 10, b = 40, c = 50
⚠️ Important Rules:
Default arguments must be on the right side.
void test(int a = 10, int b = 20); ✅ void test(int a = 10, int b); ❌ // Not allowedDefault values are assigned from right to left.
You can define defaults either in the function declaration or definition, not both.
Example:
// Declaration (header) void print(int a = 5, int b = 10); // Definition (implementation) void print(int a, int b) { cout << a << " " << b << endl; }
🧑🏫 Use Case Example:
Default parameters are very helpful when you want to give flexibility but avoid overloading multiple functions.
void printBill(float price, float tax = 0.18) {
cout << "Total amount: " << price + (price * tax) << endl;
}
int main() {
printBill(1000); // uses default 18% tax
printBill(1000, 0.10);// uses custom 10% tax
}
Output:
Total amount: 1180
Total amount: 1100