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) {}
};
starcow
  • 51
  • 4
  • 1
    Both forms are invalid. You should use `class` with small `c` instead of `Class`. – MikeCAT Sep 28 '20 at 13:44
  • There is a difference in general, as answered in the answer this is a duplicate of. In this case you're using an `int`, so it doesn't actually matter. But in general, you can write `int x{0}` to make both equivalent. As for which is better from a code style perspective is an off-topic question here. But most people seem to agree that inline initialization is preferred, especially since that initialization is skipped if the ctor that gets called uses an initializer for that member. So it doesn't actually have any overhead (there's no "double initialization.") – Nikos C. Sep 28 '20 at 14:02

1 Answers1

1

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.

dfrib
  • 70,367
  • 12
  • 127
  • 192