C++ 17: Aggregate Improvements
C++17 extends how aggregates can be initialised, but first what are “aggregates”?
Aggregates are either arrays, or simple C-like classes that have no user-provided constructors, all members public, no virtual functions. Before C++17 they could not have base classes either.
Before you could do the following to initialise an aggregate:
struct agg
{
int id;
string name;
};
agg b{ 1, "name" };
With C++17 you can also do:
struct agg_base
{
int id;
string name;
};
agg_base b{ 1, "name" };
struct agg_derived : agg_base
{
string tag;
};
agg_derived d{ {2, "name2"}, "tag" };
Curly brackets in the last line initialise base members first.
Why is this useful? Deriving a structure from another would disable aggregate initialisation before C++17, so you would have to declare custom constructors - more work 👷♂️
To contact me, send an email anytime or leave a comment below.