Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{} vs. () initialization of a class member [duplicate]

I do not understand why the following code compiles ?

struct A{ A(int); }; struct B{ A a{1}; };

but this does not:

struct A{ A(int); }; struct B{ A a(1); };

error: expected ',' or '...' before numeric constant

Is there some reason the compiler does not accept the second form? I am aware of the most vexing parse ambiguiy, but I do not think this question is related.

EDIT: As Bo explains in the comments below, I was wrong. The question is related to vexing parse after all.

I tried this on gcc-5.1.0 with --std=c++11

like image 420
oo_miguel Avatar asked Dec 25 '22 13:12

oo_miguel


1 Answers

In-class initialization of non-static members was added after the brace syntax was introduced, and to avoid confusion such as most-vexing-parses, it was made to work only with the brace syntax for direct-initialization (copy initialization is also permitted).

The syntactic construct is named brace-or-equal-initializer (in C++11 and C++14, as chris notes in a comment, C++1z changes the name).

like image 175
Ben Voigt Avatar answered Jan 04 '23 23:01

Ben Voigt