Default Parameters in C++ Functions

In C++, you can assign default values to function parameters. If an argument is not provided, the default value is used.

Example: Function with Default Parameters

#include <iostream>

void greet(std::string name = "Guest") {
    std::cout << "Hello, " << name << std::endl;
}

int main() {
    greet("Akila");  // Output: Hello, Akila
    greet();         // Output: Hello, Guest
    return 0;
}

Explanation: name has a default value "Guest". When greet is called without an argument, "Guest" is used.

Key Takeaways

  • Default parameters provide flexibility in function calls.
  • If no argument is given, the default value is used.
  • Default parameters are defined in the function declaration.