Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't initialize a struct using an initializer list if it inherits? [duplicate]

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?

like image 705
Lynn Avatar asked Sep 02 '25 14:09

Lynn


1 Answers

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.

like image 147
Shafik Yaghmour Avatar answered Sep 05 '25 03:09

Shafik Yaghmour