Why must const members be initialized in the constructor initializer rather than in its body?

后端 未结 3 476
后悔当初
后悔当初 2020-11-30 21:04

Why must class members declared as const be initialized in the constructor initializer list rather than in the constructor body?

What is the difference

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 21:44

    const and reference variables must be initialized on the line they are declared.

     class Something  
     {  
         private:  
          const int m_nValue;  
         public:  
          Something()  
          {  
              m_nValue = 5;  
          }  
      };
    

    would produce code equivalent to;

    const int nValue; // error, const vars must be assigned values immediately  
    nValue = 5; 
    

    Assigning const or reference member variables values in the body of the constructor is not sufficient.

    C++ provides another way of initializing member variables that allows to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list.

    You can assign values to variables in two ways: explicitly and implicitly: view plaincopy to clipboardprint?

    int nValue = 5; // explicit assignment  
    double dValue(4.7); // implicit assignment  
    

    Using an initialization list is very similar to doing implicit assignments.

    Remember that the member initialization list, used to initialize base and member data objects, is in the definition, not declaration of the constructor.

    More on cpp-tutorial and Code Wrangler.

提交回复
热议问题