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 : )
.h file:
class ExampleClass{
public:
ExampleClass();
private:
const std::string& string_member_variable_ = "Sample Text";
}
or
.h file:
class ExampleClass{
public:
ExampleClass();
private:
const std::string& string_member_variable_;
}
.cpp file:
ExampleClass::ExampleClass() : string_member_variable_("Sample Text") {}
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?