c++constructorheaderinitializationmember-variables

C++ Initialize const class member variable in header file or in constructor?


I just wanted to ask what's the best practice for initializing const class member variables in C++, in the header file or in the constructor?

Thanks : )

In the header file:

.h file:

class ExampleClass{

public:
ExampleClass();

private:
const std::string& string_member_variable_ = "Sample Text";
}

or

In the constructor:

.h file:

class ExampleClass{

public:
ExampleClass();

private:
const std::string& string_member_variable_;
}

.cpp file:

ExampleClass::ExampleClass() : string_member_variable_("Sample Text") {}

Solution

  • They both are not exacly the same, with the constructor initialisation one disadvantage is that you need to maintain the order of initialisation Also if you use .cpp and .h, you may need to always switch to cpp to find the initialised values.

    This is already answered in this question C++11 member initializer list vs in-class initializer?