Explain the concept of default argument with an example.
SOLUTION....
Default arguments in C++
Definition (short):
A default argument gives a parameter a value that the caller can omit. If the caller does not provide that argument, the compiler supplies the default at the call site.
Why useful:
They simplify calls and reduce the need for many overloads when sensible defaults exist.
Key rules & behavior (concise)
Default parameters must appear at the end of the parameter list (trailing parameters only).
Defaults are normally specified once, usually in the function declaration (or inside a class for member functions). Omit them in the separate definition.
The default expression is evaluated at call time, so it can reflect current values of global/static variables used in the default.
Default arguments are not part of a function’s signature and do not participate in overload resolution. Mixing overloads and defaults can lead to ambiguous or surprising calls — use care.
For virtual functions the function body is dispatched dynamically, but the default argument value is chosen statically from the type used at the call site (the static type). This can be surprising if base and derived provide different defaults.
Example 1 — Basic usage
#include <iostream> #include <string> using namespace std; void greet(const string& name = "Guest", int times = 1) { for (int i = 0; i < times; ++i) cout << "Hello, " << name << '\n'; } int main() { greet(); // uses both defaults: "Guest", 1 greet("Alice"); // uses default times = 1 greet("Bob", 2); // no defaults used return 0; }