Member Initialization Lists in Constructors
In C , a colon followed by an expression after a constructor is part of a member initialization list. It serves two main purposes:
1. Calling Base Class Constructors
In derived classes, the member initialization list can be used to specify the arguments for calling the constructor of the base class. For example, in the following code:
class demo { public: demo(unsigned char le = 5, unsigned char default) : len(le) { // Body of the constructor } }; class newdemo : public demo { public: newdemo() : demo(0, 0) { // Body of derived class constructor } };
The : demo(0, 0) syntax in the newdemo constructor calls the constructor of the demo base class with arguments 0 and 0.
2. Initializing Data Members
Before executing the constructor body, the member initialization list can be used to initialize data members of the class. This is especially useful for const members that cannot be assigned in the constructor body. For example:
class Demo { public: Demo(int& val) : m_val(val) { // Body of constructor } private: const int& m_val; };
In this example, the : m_val(val) syntax initializes the m_val const reference data member with the value of the constructor argument val.
The above is the detailed content of How Do Member Initialization Lists Work in C Constructors?. For more information, please follow other related articles on the PHP Chinese website!