C++ Default Parameters

πŸ”§ C++ Default Parameters

Default parameters allow a function to use predefined values for parameters if no argument is provided during the function call.
They make functions more flexible and easier to use.


πŸ”Ή 1. Basic Example

void greet(string name = "Guest") {
cout << "Hello " << name;
}
greet(); // Hello Guest
greet(“Sanjit”); // Hello Sanjit


πŸ”Ή 2. Default Parameters with Return Value

int add(int a, int b = 10) {
return a + b;
}
cout << add(5); // 15
cout << add(5, 20); // 25


πŸ”Ή 3. Multiple Default Parameters

int calculate(int a, int b = 5, int c = 2) {
return a * b + c;
}
cout << calculate(10); // 52
cout << calculate(10, 3); // 32
cout << calculate(10, 3, 4); // 34


πŸ”Ή 4. Important Rule (Very Important ⚠️)

➑ Default parameters must be declared from right to left

❌ Wrong:

void func(int a = 5, int b);

βœ” Correct:

void func(int a, int b = 5);

πŸ”Ή 5. Default Parameters in Function Declaration

Default values are usually placed in the function declaration (prototype), not in the definition.

int multiply(int a, int b = 2); // declaration

int multiply(int a, int b) { // definition
return a * b;
}


πŸ”Ή 6. Default Parameters with const

void print(const string &msg = "Hello") {
cout << msg;
}

βœ” Efficient
βœ” Safe


πŸ”Ή 7. Default Parameters with Pointers

void show(int *p = nullptr) {
if (p != nullptr)
cout << *p;
else
cout << "No value";
}

πŸ”Ή 8. Default Parameters vs Function Overloading

Using Default Parameters

void log(string msg, int level = 1);

Using Overloading

void log(string msg);
void log(string msg, int level);

βœ” Default parameters reduce extra functions


❌ Common Mistakes

void fun(int a = 10, int b = 20); // ❌ wrong placement

Default values must be last parameters.


πŸ“Œ Summary

  • Default parameters provide automatic values

  • Used when arguments are optional

  • Must be defined from right to left

  • Best placed in function declarations

  • Reduce function overloading

You may also like...