[C++ Primer Chapter 7] Constructor Revisited

Constructor initializer list

Initial values ​​for constructors are sometimes necessary

• Sometimes we can ignore the difference between data member initialization and assignment, but not always. If the member is const or reference, it must be initialized. Similarly, when a member is of a class type and the class does not define a default constructor, the member must also be initialized.

E.g:

1 class ConstRef
2 {
3 public:
4     ConstRef(int ii);
5 private:
6     int i;
7     const int ci;
8     int &ri;
9 };

Like other constant objects or references, members ci and ri must be initialized. So it will throw an error if we don't provide them with constructor initializers:

1  // error: ci and ri must be initialized 
2  
3 ConstRef::ConstRef( int ii)
 4  {
 5  // assign 
6      i=ii;   // correct 
7      ci=ii;    // error: cannot assign 
8 to const      ri= i;     // Error: ri is not initialized 
9 }

The initialization is complete as soon as the constructor body starts executing. The only chance we have to initialize a data member of a const or reference type is through a constructor initializer, so the correct form of the constructor would be:

ConstRef::ConstRef( int ii): i(ii),ci(ii),ri(i) {}   //correct: explicitly initialize references and const members

If the members are const, reference, or belong to a class type that does not provide a default constructor, we must provide initial values ​​for these members through the constructor initial value list (because if an assignment operation is performed, a default initialization must be performed first, which requires Use the default constructor for both class types).

 

Member initialization order

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324640942&siteId=291194637