liveBook · Manning

Uniform initialization

As explained in Learn C++ by Example

Brace initialization is C++ initialization syntax that uses braces to initialize objects and values.

Uniform initialization uses curly braces to initialize objects and values in C++. It provides a consistent alternative to older parentheses or assignment syntax, including int x{42}. section 1.4.1 section 2.1

Brace syntax is especially useful with containers:

  • std::vector<int> data{1} creates a vector containing one integer, whereas std::vector<int> data(1) creates a vector with one element initialized to zero. section 2.1
  • An initializer list can contain several values, such as {1, 2, 3}, and supplies the vector's contents. section 2.1
  • Braces reject narrowing conversions: constructing vector<int> from {1, 2.3} produces a compiler error instead of silently converting the double. section 2.1
  • The syntax also initializes empty or calculated values, as in int n{} and std::vector next_row{1}. section 2.2.2 section 3.3.3

Generating Pascal's triangle

Initialize the first row with std::vector<int> next_row{1}, then add calculated values with emplace_back. Braces express the known starting value while the vector grows procedurally. section 2.2.2

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();
}

Inspect a complete C++ 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 syntax, initializer-list behavior, constructor differences, and narrowing prevention, while deferring initialization's more complicated edge cases.
Examples
Demonstrates scalar initialization, vector construction, Pascal's triangle rows, and random prime generation.
What it assumes
Assumes basic C++ variables, references, std::vector, and stream syntax, while teaching brace initialization from introductory examples.
What you can do after
Apply it via C++11-or-later brace syntax to initialize values and containers while detecting narrowing conversions.
How it connects
Connects uniform initialization with initializer lists, constructors, std::vector, narrowing conversions, and range-based for loops.

Also explained in

Compare how 2 books explain uniform initialization →

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.