I'm puzzled by this fragment of (C++14) code I wrote:
struct B {};
struct C { int m; };
struct D : B { int m; };
int main() {
C c = { 1 }; // this works
D d = { 1 }; // this doesn't work
}
I'm fine writing a constructor for D
myself, but I can't find a good explanation for why the struct D
is no longer initializable with an initializer list. All I changed was make it inherit from a completely empty class -- I suppose I somehow made it behave less struct-like.
How exactly does my compiler handle the structs C
and D
differently?
It works for C
because it is an aggregate and therefore it is using aggregate initialization but D
is not an aggregate because it has a base class. The obvious work-around as you mention is to write a constructor.
This is covered in the draft C++ standard section 8.5.1
Aggregates [dcl.init.aggr] with emphasis mine:
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
There is a proposal: Extension to aggregate initialization to remove that restriction. As chris points out this was accepted by Evolution Working Group but as far as I understand now needs to accepted by Core as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With