Reputation: 453
I have a problem with initialization of a const class member. I have to do many calculations before initialization of the const member, so I can't use this syntax
Class::Class(int value) : value(value) {}
I wish to initialize the member in the constructor body, for example:
Class::Class(int value) {
if (Function1(value)) {
this->value = value;
Function2(&this->value);
}
else
this->value = value * 2;
}
Is it possible? Hope for your help!
Upvotes: 0
Views: 153
Reputation: 29965
Collect all the calculation into a static calculation function.
struct Class {
static int calcValue(int value) {
if (Function1(value) {
Function2(&value);
return value;
}
return value * 2;
}
Class(int val)
: value(calcValue(val))
{}
};
Upvotes: 2