For example, the following constructor is in error:
class ConstRef { public: ConstRef(int ii); private: int i; const int ci; //常量 int &ri; //引用 }; // no explicit constructor initializer: error ri is uninitialized ConstRef::ConstRef(int ii) { // assignments: i = ii; // ok ci = ii; // error: cannot assign to a const ri = i; // assigns to ri which was not bound to an object }
Remember that we can initialize but not assign to const objects or objects of reference type. By the time the body of the constructor begins executing, initialization is complete. Our only chance to initialize const or reference data members is in the constructor initializer. The correct way to write the constructor is
// ok: explicitly initialize reference and const members ConstRef::ConstRef(int ii): i(ii), ci(i), ri(ii) { }
We must use an initializer for any const or reference member or for any member of
a class type that does not have a default constructor.
By routinely using constructor initializers, we can avoid being surprised by compile-time
errors when we have a class with a member that requires a constructor initializer.