Function/Variable Scope   «Prev  Next»
Lesson 3 Default arguments
Objective Default function arguments can save time in writing C++ program.

C++ Default Function Arguments

Default function arguments in C++ save time and effort by allowing a function to be called with fewer arguments than it is defined to accept. This reduces redundancy, simplifies function calls, and improves code readability and maintainability.
✅ Explanation
A default argument provides a value that is automatically assigned to a parameter if no value is provided in the function call.
📌 Syntax Example
#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
  1. Fewer Overloads Needed

    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
        
  2. Simplifies Function Calls

    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
        
  3. Easier to Maintain

    If you change the logic of a default value, it only needs to be updated in the function declaration, not every call site.

⚠️ Caveats
  • Default arguments must be provided from right to left (trailing parameters).
  • They are typically placed in function declarations in headers, not definitions in source files.

✅ Summary
Default arguments:
  • Reduce boilerplate code
  • Improve clarity
  • Eliminate the need for multiple overloads
  • Make APIs easier to use and evolve

They’re a powerful tool in object-oriented and generic C++ programming, especially when designing class interfaces.

Background Theory and Example for default values

1. Background Theory: Default Arguments in C++
Definition: Default arguments allow you to specify default values for function parameters. If a caller omits an argument, the compiler substitutes the default value.
Key Rules:
  • Right-to-Left Initialization: Defaults must be specified from the rightmost parameter first.
    void foo(int a, int b = 10);      // Valid
    void bar(int a = 5, int b);      // Error: Missing default for 'b'
        
  • Single Evaluation: Default arguments are evaluated at call time (not at function definition).
  • Header-Only: Defaults are typically declared in the function declaration (usually in headers).

C++23 Enhancements:
  • Lambda Default Arguments: Lambdas can now have default parameters.
  • Non-Static Member Initializers: Defaults can use member variables (with restrictions).

2. Example: Default Arguments in C++23
(A) Basic Function with Defaults
#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
}

(B) C++23 Lambda with Default Arguments
#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!"
}

(C) Defaults with Member Functions (C++23)
#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
}

Key Takeaways
  1. Defaults simplify APIs by reducing overloads.
  2. C++23 expands usability (lambdas, member-dependent defaults).
  3. Order matters: Defaults must trail non-default parameters.

Compilation: Use `-std=c++2b` (GCC/Clang) or `/std:c++latest` (MSVC) to enable C++23 features.

C++ Formal Parameter

A formal parameter can be given a default argument. This is usually a constant that occurs frequently when the function is called. Using a default function argument means that you don't have to declare this default value at each function invocation.
  • Example
    The following function illustrates the point:
    //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);
    }
    

We assume that most of time the function is used to return the value of n squared.
sqr_or_power(i + 5)     //computes (i + 5) * (i + 5)
sqr_or_power(i + 5, 3)  //computes (i + 5) cubed

Only the trailing parameters of a function can have default values.

SEMrush Software