When multiple const properties of a C++ class depend on some intermediate calculation, what is the simplest way to initialize them?
For example, how do I correct the constructor for the class below?
class MyClass {
public:
const int a;
const int b;
MyClass() {
int relatedVariable = rand() % 250;
a = relatedVariable % 100;
b = abs(relatedVariable - 150);
}
};
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.
Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile . The object becomes const after the constructor completes.
An initializer for a constant is required. You must specify its value in the same declaration.
This will kinda work for those of us who happen to prefer being less advanced in their coding:
class MyClass {
public:
int iamStupid; /* K.I.S.S. */
const int a;
const int b;
MyClass()
: iamStupid(rand() % 250)
, a(iamStupid % 150)
, b(abs(iamStupid - 150))
{}
};
The additional member presents an unnecessary overhead — which may or may not be significant for the task at hand. OTOH, the code is simple.
Remember to declare iamStupid
before a
and b
! (see comments)
Here's a roundabout solution using delegating constructors:
class MyClass
{
MyClass(int aa, int bb) : a(aa), b(bb) { }
static MyClass Maker() { int x = /* ... */; return MyClass(x * 2, x * 3); }
int const a;
int const b;
public:
MyClass(MyClass const &) = default;
MyClass() : MyClass(Maker()) { }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With