liveBook · Manning

Initializer list

As explained in Learn C++ by Example

An initializer list is a brace-enclosed sequence of initial values used to initialize an object or pass initialization values to a construct.

An initializer list is a brace-enclosed sequence of values used to initialize an object directly. For example, std::vector<int> data{ 1 } creates a vector containing one integer. The braces select initializer-list construction, while std::vector<int> data( 1 ) treats 1 as the number of elements. section 2.1

Brace initialization also works for individual values, as in int x{ 42 }. It helps prevent narrowing conversions: initializing a vector of int with {1, 2.3} produces a compiler error because 2.3 cannot safely become an int. This broad use of braces is called uniform initialization. section 2.1

Initializer lists are useful when values are known at the point of construction:

  • Initialize containers with their contents, such as std::vector<int> data{ 1 }. section 2.1
  • Create a temporary sequence of enumeration values for iteration, such as the four card suits. section 5.1.5
  • Initialize objects inside containers, such as Card{ FaceValue(value), suit }. section 5.1.5

Building a deck of cards

A deck contains one card for each combination of four suits and thirteen face values. Instead of iterating directly over the enumeration, a brace-enclosed list supplies the suits: {Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades}. A range-based for loop visits each suit, while Card{ FaceValue(value), suit } initializes each card. section 5.1.5

Listing 2.1 Filling and displaying a container
#include <iostream>                 #1
#include <vector>                   #1
 
void generate_triangle()
{
    std::vector<int> data{ 1 };     #2
    for (auto number : data)        #3
    {
        std::cout << number << ' ';
    }
    std::cout << '\n';
}
 
int main()
{
    generate_triangle();
}

See a complete example that initializes a vector with braces and displays its contents using a range-based for loop. section 2.1

How Learn C++ by Example covers it

How deep it goes
Explains brace syntax, constructor ambiguity, narrowing prevention, and practical container use without exploring initialization's full complexity.
Examples
Uses vector initialization, an integer declaration, and a card-deck suit list as concrete examples.
What you can do after
Apply it via std::vector, std::array, and object construction while avoiding unintended counts and narrowing conversions.
How it connects
Connects initializer lists with uniform initialization, vectors, arrays, narrowing conversions, enumerations, and range-based for loops.

Also explained in

Compare how 2 books explain initializer list →

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.