Is it good practice when writing C++11 code to set default values for class members in the header file of the class?
Or is it better to do this in the constructor of the class?
EDIT:
I mean:
foo.h:
#include <string>
using std::string;
class Foo{
private:
string greet = "hello";
public:
Foo();
};
VS
foo.cpp (of course with the necessary header file, but without the in-class initialization):
Foo::Foo(){
greet = "hello";
}
Which one is better and why?
Foo::Foo() : greet("hello") { }
– this avoids default initialisation + assignment in favour of direct initialisation by value. For complex types, this can make a significant difference, more important, though: Some types (references, constant members, non-default constructible ones) only can be initialised that way (in the constructor, apart from assigning a default).