1

Is it possible to achieve such functionality, that parameter's value would default to another parameter's value if not specified?

Example:

class Health
{
public:
    // If current is not specified, its value defaults to max's value
    Health(int max, int current = max) : max_(max), current_(current) { }
    int max_;
    int current_;
};

As it is now, I am getting a compile error:

error: 'max' was not declared in this scope
Health(int max, int current = max) : max_(max), current_(current) { }
                              ^
0

2 Answers 2

8

You have to provide overload:

class Health
{
public:
    Health(int max, int current) : max_(max), current_(current) { }

    Health(int max) : max_(max), current_(max) {}
    // or `Health(int max) : Health(max, max) {}` since C++11

    int max_;
    int current_;
};
Sign up to request clarification or add additional context in comments.

Comments

0

You can default the parameter to a value that should not be accepted and then you and then check using the ? operator in the initialization

class Health
{
public:
    // If current is not specified, its value defaults to max's value
    Health(int max, int current = 0) : max_(max), current_(current == 0 ? max : current) { }
    int max_;
    int current_;
};

3 Comments

What if 0 is a valid value for current?
or use const int* current=nullptr (or optional<int>), but it seems over complicated.
@Jarod42 The pointer would be super-ugly for the caller ("what do you mean I cannot pass a literal?!"), but optional is fair game, I'd say.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.