Reimundo Heluani Reimundo Heluani - 3 months ago 12
C++ Question

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?

Answer

A function inside a delegating constructor (if avaliable, not neccessarily):

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

(const parameters passed by value are rarely useful)

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