Reputation: 31
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
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
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