1

I currently have the following:

struct MsgHeader_t
{
    int   a;
    float b;
};

which initializes a default const as

const MsgHeader_t default = { 0, 0.0f };

which was working fine. Now I have to extend it and it MUST inherit from another struct. So now I have.

struct MsgId_t
{
    unsigned int id;
};

struct MsgHeader_t : public MsgId_t
{
    int   a;
    float b;
};

But now when I try to initialize that default const (const MsgHeader_t aMessage = { 0, 0, 0.0f };) I get

error: braces around initializer for non-aggregate type 'const MsgHeader_t'

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
jiveturkey
  • 2,484
  • 1
  • 23
  • 41
  • 1
    `MsgHeader_t` is POD but no longer an aggregate type https://stackoverflow.com/questions/23808357/brace-initialization-for-inherited-pod – Cory Kramer Apr 14 '20 at 15:45

2 Answers2

1

Once you have inheritance, then your class can no longer be an aggregate type. From this Draft C++ Standard (bold italics mine):

8.5.1 Aggregates

1 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).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • I made be a little dense in my reading but does that mean I should be able to provide a ctor for it and all should be good? Also, what is a POD? – jiveturkey Apr 14 '20 at 15:50
  • POD = "Plain Old Data." Yes, a constructor would work, and this could use 'brace' initialization for the base class. Also, it's not for me to assess your [specific gravity](https://www.google.co.uk/search?source=hp&ei=YNyVXuPQEZGxU8j4lagI&q=specific+gravity&oq=specific+gravity&gs_lcp=CgZwc3ktYWIQAxgAMgIIADICCAAyAggAMgIIADICCAAyAggAMgIIADICCAAyAggAMgIIADoFCAAQgwFKJwgXEiMwZzgzZzk1ZzY2ZzgwZzExM2c2NWc1NWc2NGc3MGc3Nmc3MUobCBgSFzBnMWcxZzFnMWcxZzFnMWcxZzFnNWcyUPsFWO4dYIAlaABwAHgAgAFliAHaCJIBBDE1LjGYAQCgAQGqAQdnd3Mtd2l6&sclient=psy-ab). – Adrian Mole Apr 14 '20 at 15:55
  • Very funny. Thanks for making me look things up :) – jiveturkey Apr 14 '20 at 15:58
0

Note that since C++17, you might do, as you expect:

  • const MsgHeader_t aMessage = { 0, 0, 0.0f };. Demo
  • or more properly const MsgHeader_t aMessage = { {0}, 0, 0.0f };. Demo
Jarod42
  • 203,559
  • 14
  • 181
  • 302