You could make a
and b
private, and provide getters to access their values from outside the class.
class MyClass
{
private:
int a, b; // private
public:
int getA() { return a; }
int getB() { return b; }
MyClass()
{
int relatedVariable = rand() % 250;
a = relatedVariable % 100;
b = abs(relatedVariable - 150);
}
};
Or, you could just use subobject initializers and cache the random number somehow. Turning the optimization on might even remove the temporary variable in the generated program text.
class MyClass
{
private:
int temp; // this is a workaround
public:
const int a;
const int b;
MyClass() : temp(rand() % 250), a(temp % 100), b(abs(temp - 150)) {}
};
Remember that subobject construction happens in the order that members are declared in the class, and that the order of subobjects in the initialization list is ignored.
Or, you can be lazy, and only store the initial random number, and generate a, b
on demand.