There is a class

class object { public: object(); private: const double mass; }; 

Initialization of const double mass in the constructor works only like this:

 object::object(): mass(1) { } 

Why does not pass this option?

 object::object() { this->mass = 1; } 

And how, in this case, to initialize const members of the class, which must first be calculated relative to the input parameters of the constructor?

What options in C ++ are convenient for declaring / initializing const class members?

    1 answer 1

    When the body of the constructor is executed, all the members of the object data are already created. Therefore, in this constructor

     object::object() { this->mass = 1; } 

    in a sentence

      this->mass = 1; 

    an assignment operator is used that cannot be used with constant objects.

    If you need to determine the value of a constant data member based on some calculations, then use some, for example, a static function - a member of the class as the initializer.

     object::object( some_argument ): mass( some_function( some_argument ) ) { } 

    Function arguments do not have to be constructor arguments. You can use static data members of a class, not statically data members that have already been initialized in the initialization list (lags in the class declaration must precede, or objects that are within the scope of the constructor definition.

    The following is an example.

     #include <iostream> class Object { public: Object( double x ) : x ( 2 * x ), mass( init( this->x ) ) { } double get_mass() const { return mass; } private: double x; const double mass; static double init( double x ) { return x < 0 ? -x / 2 : x; } }; int main() { Object obj( 10 ); std::cout << obj.get_mass() << std::endl; return 0; } 
    • Why is a static class function required for initialization? Isn't the ordinary class function in the scope of the constructor? Or is this not the case? - Gordory
    • @Gordory I only cited a static function as an example, but you can call non-static functions, including even virtual functions. - Vlad from Moscow
    • @Gordory is not a static member function that can use non-initialized class members, so this option is not very good. - αλεχολυτ
    • The @VladfromMoscow virtual function call in the constructor or constructor initializer is a dangerous approach, in any case, the version for the current constructed class will be called. And this function may well be "clean" - we get a "pure virtual call". - αλεχολυτ
    • @alexolut I provide information about what is allowed, and not about what specificity of a particular call. - Vlad from Moscow