0

I have browsed SO regarding initializer lists and member initialization and haven't found an answer to this specific issue. Please excuse me if it does turn out to be a duplicate.

I'm browsing C++ source code where a member FILE* of a struct is initialized like so:

struct Something {
    FILE* d_fp{0};
}

I have Googled it, and I understand the concept of initialization using an initializer list constructor.

I understand that if no dedicated initializer-list constructor is present on the instantiated type, a different constructor with a matching number of arguments is called. So saying MyType o{0} is the same as MyType o(0). Please correct me if my understanding is false.

However, in this case, changing the code to read FILE* d_fp(0) results in compiler errors:

main.cpp:47:11: error: expected ';' at end of member declaration
   47 |     FILE* d_fp(0);
      |           ^~~~
      |               ;
main.cpp:47:16: error: expected unqualified-id before numeric constant
   47 |     FILE* d_fp(0);
      |                ^
main.cpp:47:16: error: expected ')' before numeric constant
   47 |     FILE* d_fp(0);
      |               ~^
      |                )

So two questions follow:

  1. Why does d_fp(0) not do the same thing as d_fp{0} in this case?

  2. What might be the reason a programmer chooses d_fp{0} initialization instead of the more intuitive d_fp = 0? Is it simply a matter of taste, or is it not actually the same thing?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • 1
    @AdrianMole `FILE* d_fp(0);` is not the MVP. It would be legal and correct if it wasn't inside a class. Inside a class, you can only use `{}` or `= ...` syntax to initialize a member. – NathanOliver May 19 '20 at 19:51
  • @NathanOliver Fair comment. Just that I was a bit vexed by clang's message: **error : expected parameter declarator**. (Suggesting it sees the start of a function declaration at `d_dp(` but then doesn't get one.) – Adrian Mole May 19 '20 at 19:53
  • @AdrianMole Clang is saying that because in a class, the only thing that has a `()` after the name is a function, so that's what clang is expecting but not getting. – NathanOliver May 19 '20 at 19:55
  • 1
    @NathanOliver OK - Then it's a *slightly* vexing parse. :) – Adrian Mole May 19 '20 at 19:56

0 Answers0