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?
CodePudding user response:
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); }
};
CodePudding user response:
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
}
};
