Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does having a base class disqualify a class from being aggregate?

Tags:

c++

c++11

What is it about having an aggregate public base class (or even multiple aggregate public base classes) that would make a class lose the nice properties of aggregate classes?

Definition of "aggregate base class" from http://en.cppreference.com/w/cpp/language/aggregate_initialization http://en.wikipedia.org/wiki/C++_classes#Aggregate_classes


The nice properties of aggregate classes:

  • Without defining a constructor, an aggregate type can be initialized by passing in a brace-enclosed list of values to initialize its members (or base classes, if they had allowed them).
  • Aggregate types are considered "simple" (a generalization of PODs), and can be used as a literal type for the purposes of constexprs.

Abridged example of initialization from http://en.cppreference.com/w/cpp/language/aggregate_initialization#Example:

#include <string>
#include <array>
struct S {
  int x;
  struct Foo {
    int i;
    int j;
    int a[3];
  } b;
};

int main()
{
  S s1 = { 1, { 2, 3, {4, 5, 6} } };
  S s2 = { 1, 2, 3, 4, 5, 6}; // same, but with brace elision
}

See also: What are Aggregates and PODs and how/why are they special?

like image 230
leewz Avatar asked Nov 07 '13 21:11

leewz


1 Answers

Since C++17 classes that have public, non-virtual base classes can be aggregates.

struct Base1 {
 int a, b;
};
struct Base2 {
 int c;
};

struct Foo : Base1, Base2 {
    int d, e;
};

Objects of struct Foo can be aggregate-initialized. The following initializations are equivalent:

Foo foo {Base1{1, 2}, Base2{3}, 4, 5};
Foo foo {{1, 2}, {3}, 4, 5};
Foo foo {1, 2, 3, 4, 5};
like image 114
Kaznov Avatar answered Sep 28 '22 07:09

Kaznov