oveyis
oveyis

Reputation: 31

Using the default value for a leading argument while specifying the others

I am wondering how I can skip overriding a parameter in a C++ function. For example, looking at the function below, if output has 1 parameter, you can just call it without sending any parameters, like output();

That will output 5 since xor has a default value of 5. However, if I want to override "vor", and leave xor to its default value, how do I do that?

output(NULL, 20);

Above didn't work, it just initalized xor to 0.

void output(int xor = 5, int vor = 15) {
    cout << xor << " " << vor << endl;
}

int main()
{
    output(10, 20);
}

Upvotes: 1

Views: 49

Answers (2)

wangjunwww
wangjunwww

Reputation: 296

To purely realize what you want to achieve, you can switch the parameter order in output() like this:

void output(int vor = 15, int xor = 5) {
    cout << xor << " " << vor << endl;
}

Then you can call output(20) to override vor while keeping xor to its default value.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

If you want to override the second default argument then you have to specify the first argument.

Possible calls of the function are following

output();         // corresponds to output( 5, 15 );
output( x );      // corresponds to output( x, 15 );
output( x, y );   // corresponds to output( x, y );

where x and y are some arbitrary arguments.

Upvotes: 2

Related Questions