liveBook · Manning

Aggregate initialization

As explained in Learn C++ by Example

Aggregate initialization initializes an aggregate object from a brace-enclosed sequence of initializers for its elements or members.

Aggregate initialization creates an aggregate object from a brace-enclosed sequence of member initializers. Unlike an initializer list, the values may have different types and must follow member order. section 5.1.1

For a simple Card aggregate with an int followed by a Suit:

  • Card card{2, Suit::Clubs}; initializes both members in declaration order. section 5.1.1
  • Card card{2}; initializes the value and default-initializes the remaining suit member. section 5.1.1
  • Card card{Suit::Clubs}; is not valid because omitted initializers may occur at the end, not at the beginning. section 5.1.1
  • Using Suit::Clubs makes the construction clearer and less error-prone than supplying two integers. section 5.1.1

Initializing a deck

A fixed-size array can initialize selected elements with aggregate initialization: std::array<Card, 52> deck{Card{FaceValue(2), Suit::Hearts}}; places a two of hearts first and default-constructs the remaining cards. section 5.1.5

std::array<Card, 52> deck{Card{FaceValue(2), Suit::Hearts}};

Inspect a complete aggregate initializer that seeds an array with one card while leaving the remaining elements default-constructed. section 5.1.5

How Learn C++ by Example covers it

How deep it goes
Explains heterogeneous member ordering, trailing defaults, and partial array initialization, but defers broader aggregate rules.
Examples
Uses Card values, suits, a 52-card deck, and an extended deck beginning with two jokers.
What it assumes
Assumes basic structs, arrays, enums, and brace syntax while reinforcing the difference between aggregates and initializer lists.
What you can do after
Apply it via C++ brace syntax to construct aggregates and initialize selected elements of fixed-size arrays.
How it connects
Connects aggregate initialization with uniform initialization, initializer lists, scoped enumerations, and std::array.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.