Aggregate class definition and usage analysis in C++

  • 2020-05-27 06:33:42
  • OfStack

This article illustrates an example of an aggregate class in C++. I will share it with you for your reference as follows:

The aggregate class is an undefined constructor with no private (private) and protected (protected) non-static data members, no base classes, and no virtual functions. Such a class can be initialized by enclosing curly braces separated by commas. The following code has the same syntax in C and C++ :

struct C 
  int a;
  double b;
struct D 
  int a;
  double b;
  C c;
// initialize an object of type C with an initializer-list
C c = { 1, 2 };
// D has a sub-aggregate of type C. In such cases initializer-clauses can be nested
D d = { 10, 20, { 1, 2 } };

If a class contains a user-defined constructor, use {xx, xx,... } to initialize its object, and the compiler will report an error

vc -- error C2552: "xx" cannot initialize a non-aggregate with a list of initializers
gcc -- error: xx must be initialized by constructor, not by '{... } '

The aggregation is defined as:

An array of

Classes, structures, and unions without:

The constructor
A private or protected member
The base class
Virtual functions

The compiler does not allow the use of data types in aggregates that contain constructors.

I hope this article is helpful to you C++ programming.

Related articles: