Reimundo Heluani Reimundo Heluani - 1 year ago 80
C++ Question

How to initialize const member requiring computations to be performed?

I understand that for a class

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

I could initialize
in the initializer list like so:

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download