Debadipto Biswas
Debadipto Biswas

Reputation: 31

How to pass a struct member in one of the struct's method as default parameter?

I want to pass the variable a as a default parameter in method func().

struct S {
    int a;
    int func(int b = a) {
        // do something
    }
};

On compiling it shows error. Is it possible to somehow get around this?

Upvotes: 3

Views: 129

Answers (2)

Jarod42
Jarod42

Reputation: 217275

Another alternative is to use std::optional:

struct S {
    int a;
    int func(std::optional<int> ob = std::nullopt) {
        int b = ob.value_or(a);
        // do something
    }
};

Upvotes: 2

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

It is not possible to use the value of a non-static member as default argument. You can use an overload instead:

struct S {
    int a;
    int func(int b) {
        // do something
    }
    int func() { return func(a); }
};

Upvotes: 7

Related Questions