Member Initialization List in Constructors
In C , constructors can initialize data members using a member initialization list. This list appears after the constructor name, separated by a colon (:).
Inheritance and Member Initialization List
The member initialization list can also be used to call base class constructors. In the provided code:
class demo { public: demo(unsigned char le = 5, unsigned char default) : len(le) { ... } }; class newdemo : public demo { public: newdemo(void) : demo(0, 0) { ... } };
demo(0, 0) in the constructor of newdemo calls the constructor of its base class demo with the arguments 0 and 0, initializing the len member.
General Usage of Member Initialization List
Outside of inheritance, the member initialization list allows for:
Initialization of Data Members Before Constructor Body:
Members that are not const can be initialized in the initialization list before the constructor body executes. This ensures that the member is initialized regardless of the constructor's flow.
Initialization of Const Data Members:
Const data members can only be initialized in their declaration or with a member initialization list.
Example:
class MyClass { public: MyClass(int value) : value(value) // Initialize const member in initialization list { ... } private: const int value; };
The above is the detailed content of How Do Member Initialization Lists Work in C Constructors and Inheritance?. For more information, please follow other related articles on the PHP Chinese website!