Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize const member requiring computations to be performed?

I understand that for a class

class A { 
     const int myint;
  public:
     A (const int yourint);
     A (const std::string yourstring);
};

I could initialize myint in the initializer list like so:

A::A (const int yourint) : myint (yourint) {};

However, what is the proper way of initializing myint from the second constructor if the the data required to compute it comes say from a string and the computations may be involved?

like image 723
Reimundo Heluani Avatar asked Aug 31 '25 03:08

Reimundo Heluani


1 Answers

Use a function call inside a delegating (if avaliable, not neccessarily) constructor's member initialization list:

A::A(std::string const& yourstring) : A(compute_myint(yourstring)) {};

Pass std::string by const&, not just const, while you're at it.

compute_myint can be non-member, static member, possibly not accessible from outside the class, whichever makes the most sense.

like image 190
LogicStuff Avatar answered Sep 02 '25 16:09

LogicStuff