I have a C++ class with two data members, e.g.,
class mytest() {
public:
mytest():
a_(initA()),
b_(initB())
{};
virtual ~mytest() {};
private:
double initA() {
// some complex computation
}
double initB() {
// some other complex computation
}
private:
const double a_;
const double b_;
}
Unfortunately, though, initA
and initB
cannot be separated as sketched above. Both a_
and b_
can be initialized by one big complex computation, where the value of b_
depends on an intermediate result in the computation of a_
, e.g.,
void mytest::init() const {
const double a = 1.0 + 1.0; // some complex computation
const double b = 2*(a + 1.0); // another complex computation
a = 2 * a; // even more complex, wow
// Now, a and b contain the data from which a_ and b_ should be initialized.
}
I would like to keep a_
and b_
separate (and const
) variables (and not put them in a std::tuple
or similar). However, I don't know if it's possible to initialize a_
and b_
separately from a single function.
Any hints?
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.
The safest approach is to initialise every variable at the point of construction. For class members, your constructors should ensure that every variable is initialised or that it has a default constructor of its own that does the same.
A field marked as const can be initialized only at compile time. You need to initialize a field at runtime to a valid value, not at compile time. This field must then act as if it were a constant field for the rest of the application's life.
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.
You can add extra intermediate function/struct to initialize your class
with delegating constructor:
struct MytestHelper
{
double a;
double b;
};
MytestHelper someComplexComputation(); // feed `a` and `b`
class mytest() {
public:
mytest() : mytest(someComplexComputation()) {}
virtual ~mytest() {};
private:
mytest(const MytestHelper& h) : a_(h.a), b_(h.b) {}
private:
const double a_;
const double b_;
};
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