How to initialize const member requiring computations to be performed?
Here you would want to use delegating constructors, if you can, or you could compute in the ctor. See my second example for the second option. An example for your class would be:
Option 1: Delegating Constructors: C++11 forward
class A {
const int myint;
static int parse_int(const std::string& string) {/*...*/}
public:
A (const int yourint) : myint{yourint};
A (const std::string yourstring) : A{parse_int(yourstring)};
}
By the way, since parse_int
only computes integers, then it could be static
, meaning it does not require a class instance to be used. Of course, there is no requirement, as the function could be a member just as well, (non static
), although static
is safer, since it will almost always guarantee the construction of the object.
Option 2: Constructor Computation, non delegating
This method could be used in any C++ version.
class A {
const int myint;
static int parse_int(const std::string& string) {/*...*/}
public:
A (const int yourint) : myint(yourint);
A (const std::string yourstring) : my_int(parse_int(yourstring));
}
Just use a member function.
Keep in mind that it's safer (i.e. less error-prone) to use a static
member function for things like this than a non-static one, because the class isn't fully initialized yet when the function is called.
class A {
const int myint;
public:
A(const int x) : myint(x) {}
A(std::string const& s) : myint(compute(s)) {}
private:
static int compute(std::string const& s) { return (int)s.length(); }
};
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.