If I want to assign a default value to an instance variable, which method is to be preferred? Is there a difference?
Class Foo {
int x = 0;
};
Class Foo {
int x;
Foo() : x(0) {}
};
If I want to assign a default value to an instance variable, which method is to be preferred? Is there a difference?
Class Foo {
int x = 0;
};
Class Foo {
int x;
Foo() : x(0) {}
};
You may choose to setup an initialization strategy for the member variable both using designated member initializers as well as member initializer list in constructors. If a given constructor does not initialize a given non-static data member, initialization of that data member will fall back on a designated member initializer, if present.
#include <iostream>
template<std::size_t TAG_N> struct Tag{};
struct Foo {
int x{42};
// ^^^^ - designated member initializer (DMI)
Foo() {} // Use DMI -> x is 42
Foo(Tag<0>) {} // Use DMI -> x is 42
Foo(Tag<1>) : x(1) {} // Initialized in mem. init list -> x is 1.
};
int main() {
std::cout << Foo{}.x << " "
<< Foo(Tag<0>{}).x << " "
<< Foo(Tag<1>{}).x << "\n";
// 42 42 1
}
Choosing which approach would enter the domain of opinion-based, but favoring consistency is never a bad advice, and [opinionated] many industry experts recommend using designed member initializers in classes which provide more than one constructor, to avoid the pitfall of e.g. adding a new member to the class but forgetting to initialize it in one the overloaded constructors' member initializer lists.