2

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") {}
Community
  • 1
  • 1
JilReg
  • 382
  • 1
  • 3
  • 16

3 Answers3

3

Arguments for "in the constructor":

  • Code style consistency of old codebase.
  • The need to build the code on different platforms with different compilers.
  • Possible reduce of compilation time while developing. If you change the value of your constant, all units that include your header will be rebuilt.
Eugene
  • 3,335
  • 3
  • 36
  • 44
1

You can initialize in-place if using the C++11. You can also initialize in constructor. Two ways to initialize const member fields inside a class:

class MyClass{
public:
    const std::string myconst = "Hello World";  // in-place initialization C++11
};

class MyClass{
public:
    const std::string myconst;
    MyClass() : myconst("Hello World"){}    // initialize const member in a constructor
};

When it comes to non static integral constants I would opt for a constructor option. Declare a constant in the header file and initialize it inside a constructor in your source file. Another thing is that this part:

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

is wrong and your compiler will warn you that:

reference member is initialized to a temporary that doesn't persist after the constructor exits

Use const std::string instead.

Ron
  • 14,674
  • 4
  • 34
  • 47
  • Hey Ron, thanks for your fast reply. I know both is possible this is why I asked what's the better practice? : ) – JilReg Jul 17 '17 at 01:50
1

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?

Randolf
  • 125
  • 1
  • 9