Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Default Arguments in C++ Functions


C++
David Egan

Function parameters in C++ can have a default argument. If the function is declared, the default argument is specified in the declaration - NOT the function definition.

If a function declaration contains a parameter with a default argument, all subsequent parameters must also have a default argument supplied.

If your function is not declared, the default argument can be specified in the function definition.

Example

// The function declaration contains the default parameter
int sum(int a, int b = 10);

// The function definition does not contain the default parameter
int sum(int a, int b)
{
    return a + b;
}

// If there is no function declaration, the default argument is specified in the function definition:
double multiply(double a, double b = 10)
{
    return a * b;
}

int main()
{
    std::cout << sum(2) << std::endl;
    // Outputs 2 + 10 = 12

    std::cout << sum(2,2) << std::endl;
    // Outputs 2 + 2 = 4

    std::cout << multiply(2) << std::endl;
    // Outputs 2 * 10 = 20

    std::cout << multiply(2,2) << std::endl;
    // Outputs 2 * 2 = 4
}

References

Default Arguments: CPP Language reference


comments powered by Disqus