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

Viewed 315

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?

3 Answers
Related