[C++ Primer Chapter 7] Aggregate Class

Aggregate classes: Aggregate classes give users direct access to their members and have a special-property initialization syntax form.

A class is said to be an aggregate class when it satisfies the following conditions:
1. All members are public|
2. No constructors are defined
3. No in-class initializers
4. No base classes and no virtual functions

For example, the following class is an aggregate class:

struct Date
{
  int ival;
  string s;
}

We can provide a brace-enclosed member initialization list and use it to initialize the data members of the aggregate class:

//val1.ival=0; val1.s=string("Anna")
Data val1={"Anna",1024"};

 

The order of initial values ​​must match the order of declaration, that is, the initial value of the first member is placed first, then the second, and so on. The following example is wrong:

// Error: ival is not initialized with "Anna", nor can s be initialized with 1024 
Data val2={ " Anna " , 1024 };

As with the rules for initializing array elements, if the number of elements in the initializer list is less than the number of members of the class, the later members are value-initialized. The number of elements in the initial value list must never exceed the number of members of the class.

It's worth noting that explicitly initializing members of an object of a class has three distinct disadvantages:

  • Require all members of the class to be public
  • The onus of properly initializing every member of every object is left to the user of the class (not the class author). Such initialization is tedious and error-prone because it is easy for users to forget an initial value, or to provide an inappropriate initial value.
  • After adding or removing a member, all initialization statements need to be updated.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688646&siteId=291194637