Question

Since C++11 we can default construct our variables in a class, like this:

class Foo{
private:
    int bar = 0;
};

I've very rarely seen someone using this feature

Is this a good practice ?

Was it helpful?

Solution

This is a style question, but there are some considerations that are hopefully universal:

If all constructors of your class have to initialize a member the same way, because the initial value is in some profound way part of the invariants of the class, then it is both more readable and self-documenting and also shorter to use the inline initializer, and the deduplication removes a source of errors if you ever need to change the initial value.

Otherwise, if different constructors supply different initial values, then you shouldn't have an inline initializer, even though that's technically permitted.

OTHER TIPS

I dont see any bad practices in this approach. This is allowed even in Higher level languages like Java. It reduces lines of code inside constructor.

The only big disadvantage I see is that it may lead people to expose more implementation details than necessary in class definitions. Currently, if you initialize a member in MyClass.cpp, then you can easily change the value later on. If you initialize the member in MyClass.h, then a lot of recompilation could be necessary if you later change the value.

In Java, you don't have this kind of separation between header and implementation, so the situation cannot be compared to C++.

C++11 allows non-static data members to be initialized in-class.

This can often save some typing. Consider the following example:

class Foo {
public:
    Foo() : a_{5}, b_{7}, s_{"Foo"}, bar_{"Test"} {}
    Foo(int x) : a_{x}, b_{7}, s_{"Foo"}, bar_{"Test"} {}
    Foo(double d) : a_{5}, b_{g(d)}, s_{"Foo"}, bar_{"Test"} {}
    int someFunc();
private:
    int a_;
    int b_;
    std::string s_;
    Bar bar_;
};

Using in-class initialization will IMHO make the code more readable.

class Foo {
public:
    Foo() = default;
    Foo(int x) : a_{x} {} // Initialization list overrides in-class initialization.
    Foo(double d) : b_{g(d)} {} // Same here.
    int someFunc();
private:
    int a_ = 5;
    int b_ = 7;
    std::string s_{"Foo"};
    Bar bar_{"Test"};
};

I would say use it when possible. An exception is when the situation described in this answer applies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top