A stock item needs both a name and a quantity. Two separate lists can accidentally get out of step. A struct groups related fields into one record, so the item name and count travel together.
#include <string>
#include <iostream>
struct Session {
std::string title;
int seats;
};
int main() {
Session morning{"Drawing", 12};
std::cout << morning.title << '\n';
std::cout << morning.seats << '\n';
}
struct Session defines a new type. Inside its braces, each declaration names a member, also called a field. The semicolon after the closing brace finishes the type definition; do not omit it. Declaring the type does not itself create a session. Session morning{...} creates one object of that type.
The initialization values follow the field declaration order: the string initializes title, and twelve initializes seats. This simple brace initialization is called aggregate initialization. Supply both fields in these records so the intended starting state is obvious.
A dot selects a member of an object: morning.title reads the name, while morning.seats = 15 would replace the count. Members may have different types, unlike elements in a vector of integers. In a struct these members are public by default, meaning code outside the struct can access them directly.
Use a struct when the fields describe one thing. You can create several independent objects of the same type, each with its own field values. You can also copy one record into another. Editing a field of the copy then leaves the original record unchanged.
Grouping fields does not enforce rules about their values. For example, a public integer field can still be assigned a negative stock count. These simple records rely on the surrounding code to supply sensible values. The classes section will show how to put updates behind operations that preserve such rules.
The starter supplies the Item type, so you do not need to write another struct definition. In item's braces, the first value fills name and the second fills units. Replace those temporary values one at a time. The two output lines read the fields separately, letting you see which initializer each change affects.
name initializer in item to "Notebooks". Expect Item: Notebooks.units initializer in item to 14. Expect Units: 14.Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.