| Lesson 3 | Default arguments |
| Objective | Default function arguments can save time in writing C++ program. |
#include <iostream>
using namespace std;
void greet(string name = "Guest") {
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet(); // Uses default argument: "Guest"
greet("Thomas"); // Overrides default with "Thomas"
return 0;
}
💡 Time-Saving Benefits
Instead of writing multiple overloaded versions of a function, you can write one with default arguments.
void log(string message, int level = 1); // Only one version needed
You don’t need to specify all arguments every time—only the ones that vary.
// Instead of always writing:
printReport("sales", "monthly", true);
// You can allow defaults:
printReport("sales"); // Other args defaulted
If you change the logic of a default value, it only needs to be updated in the function declaration, not every call site.
void foo(int a, int b = 10); // Valid
void bar(int a = 5, int b); // Error: Missing default for 'b'
#include <iostream>
// Function declaration with defaults (C++23 compliant)
void print_message(const std::string& msg = "Hello, C++23!", int repeat = 1);
// Definition
void print_message(const std::string& msg, int repeat) {
for (int i = 0; i < repeat; ++i) {
std::cout << msg << '\n';
}
}
int main() {
print_message(); // Uses both defaults: "Hello, C++23!", 1
print_message("Custom text"); // Uses default `repeat = 1`
print_message("Hi again", 3); // Overrides both defaults
}
#include <iostream>
int main() {
// Lambda with default arguments (C++23 feature)
auto greet = [](const std::string& name = "World") {
std::cout << "Hello, " << name << "!\n";
};
greet(); // Output: "Hello, World!"
greet("Alice"); // Output: "Hello, Alice!"
}
#include <iostream>
struct Widget {
int threshold = 10; // Non-static member initializer
// Member function with default using member variable (C++23)
void check(int value, int max = threshold) const {
std::cout << (value <= max ? "OK" : "Exceeded") << '\n';
}
};
int main() {
Widget w;
w.check(5); // Uses `threshold` (10) as default for `max`
w.check(15, 20); // Overrides default
}
//k=2 is default
int sqr_or_power(int n, int k = 2) {
if (k == 2)
return (n * n);
else
return (sqr_or_power(n, k - 1) * n);
}
n squared.
sqr_or_power(i + 5) //computes (i + 5) * (i + 5) sqr_or_power(i + 5, 3) //computes (i + 5) cubed