Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: const-initialize multiple data members from one initializer function

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?

like image 976
Nico Schlömer Avatar asked Mar 22 '16 10:03

Nico Schlömer


People also ask

How do you initialize all type const data members?

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.

Should a constructor initialize all members?

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.

Can const be initialized?

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.

Do const variables need to be initialized?

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.


1 Answers

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_;
};
like image 71
Jarod42 Avatar answered Nov 06 '22 22:11

Jarod42