Initializer List Placement in Constructor Definition
When defining a class constructor, it's essential to understand the role of the member initializer list. This list initializes member variables as part of the constructor definition.
As for its placement, the initializer list is part of the constructor's definition, not its declaration. This means it's not included in the header file (.h) where the class itself is declared. Instead, it resides in the source file (.cpp) where the constructor is defined.
Example Usage
Consider the following class:
class Example { private: int m_top; const int m_size; public: Example(int size, int grow_by = 1); };
In this example, the constructor is defined as follows:
Example::Example(int size, int grow_by) : m_size(5), m_top(-1) { // ... }
The initializer list within this constructor initializes the member variables m_size and m_top. It is crucial to include the initializer list as part of the constructor's definition in the source file (.cpp).
Therefore, the correct placement of the initializer list is within the constructor's definition, not in the header file (.h) where the class is declared.
The above is the detailed content of Where Should I Place the Member Initializer List in a C Constructor?. For more information, please follow other related articles on the PHP Chinese website!