Lesson 108 +10 XP

Aggregate Initialization

Aggregate Initialization

Filling the members one dot at a time works, but when you build a struct you can set many members at once with a brace list. That is aggregate initialization.

Everything at declaration time

#include <iostream>
using namespace std;

struct Car {
  string brand;
  int year;
};

int main() {
  Car myCar { "Tesla", 2015 };
  cout << myCar.brand << " " << myCar.year << endl;   // Tesla 2015
  return 0;
}

The values in braces fill the members in declaration order:

  • brand receives "Tesla".
  • year receives 2015.

The optional equals sign

You may add = before the braces; both forms are identical:

Car v1 { "BMW", 1995 };          // direct-list syntax
Car v2 = { "BMW", 1995 };        // same meaning

Missing fields are zero-initialized

Give fewer values than members and the remaining ones become the zero value of their type:

Car part { "Tesla" };   // brand = "Tesla", year = 0
Car none {};            // brand = "",    year = 0
  • int gets 0.
  • string gets an empty string "".

Members can still change afterwards

car.year = 2020;              // update one member later
cout << car.brand << endl;    // reads fine too

TL;DR

  • Car c { "Tesla", 2015 }; sets all members in one brace list.
  • Values map to members in declaration order.
  • Car c = { "Tesla", 2015 }; means the same thing.
  • Missing members are zero-initialized (0 / empty "").
  • An empty list {} zero-fills every member.