C++ Member Initializer List

Just to clarify something that came up in some of the other answers…

There is no requirement that the initializer list be in either the source (.cpp) or header (.h) file. In fact, the compiler does not distinguish between the two types of files. The important distinction is between the contructor’s declaration and it’s definition. The initializer list goes with the definition, not the declaration.

Usually, the declaration is in a header file and the definition is in a source file, however, this is not a requirement of the language (i.e. it will compile).
It is not unusual to provide constructor definitions inline in the class declaration when the constructor is empty or short. In that case, an initializer list would go inside the class declaration, which would probably be in a header file.

MyClass.h

class MyClass
{
public:
    MyClass(int value) : m_value(value)
    {}
private:
    int m_value;
};

Leave a Comment