Mark A. Donohoe
Mark A. Donohoe

Reputation: 30458

In C++, how can you pass some parameters while leaving others as defaults?

I'm sure this has been answered here already, but search keeps returning PHP, C# and Java. I'm specifically asking about C++.

If I have a function that takes five arguments and all of them have default values, but I want to call it explicitly giving a value for the third argument, what do I pass for the first and second arguments? (I know func(,,"Third") doesn't work, neither does func(thirdArg:"Third"))

Upvotes: 2

Views: 258

Answers (4)

MrPisarik
MrPisarik

Reputation: 1290

You can make something similar on solution for default-parameters in Java constructors.

But I don't think that it's good practice in C++, especially for functions, because how have said above - position of default-parameters generally accepted after non-default parameters.

Solution achieved by using function overloading:

void Foo(int default, int nodefault){
    ...
}

void Foo(int nodefault){
    Foo(10, nodefault); //10 - is default option
}

int main(){
    Foo(3); //calls Foo(10, 3);
}

Upvotes: 2

quantdev
quantdev

Reputation: 23813

There is no direct support in the language. However an idiom often used by C++ programmers to replace the lack of bash-like positional parameters is the Named Parameter idiom..

Assuming that your function is a member method of a class, you can easily apply this idiom :

Basically, you have methods (possibly accessors) to modify the state of your object. Each method returns a non-const reference to this, allowing method chaining.

Example:

class Person{

public:

    Person& setAge(int agep) { age = agep ; return *this; }

    Person& setWeight(double weightp) { weight = weightp ; return *this; }

    Person& setName(const std::string& namep) { name = namep ; return *this; }

private:
    int age = 0;
    double weight = 0.0;
    std::string name;
};

int main(){
    Person p;

    p.setAge(42).setName("Kurt"); // set age and name, but not weight
}

Upvotes: 0

nature1729
nature1729

Reputation: 243

This is non trivial. May be you can try boost parameter. You can pass parameter as such then,

func(third_="third")

Please check =>

http://www.boost.org/doc/libs/1_56_0/libs/parameter/doc/html/index.html#named-function-parameters

Upvotes: 0

Chuck Walbourn
Chuck Walbourn

Reputation: 41127

In C++ you have to specify all the parameters up to the defaults, so it would have to be func("First","Second","Third").

C++ also requires that you have defaults at the 'end' of the parameter list, so you can't do something like func(defaulted, not-defaulted)

Both of these rules tie into the C++ overload resolution rules.

Upvotes: 5

Related Questions