10.2 — struct: a group of values

📘 Chapter 10⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Bundling data together#

A struct groups related values into one new type.

C++
struct Player{    std::string name {};    int health { 100 };    int level { 1 };};

Each value inside is called a member.

Using a struct#

C++
Player hero { "Ana", 80, 3 }; std::cout << hero.name << " has " << hero.health << " health.\n"; hero.health -= 10;   // use a dot . to reach a member
Output
Ana has 80 health.

Default values#

We gave the members starting values above. So this works too:

C++
Player newbie {};newbie.name = "Ben";   // health is 100, level is 1

Structs and functions#

Pass structs by const& to avoid copies:

C++
void printPlayer(const Player& p){    std::cout << p.name << " (level " << p.level << ")\n";}

Lists of structs#

C++
std::vector<Player> team {    { "Ana", 80, 3 },    { "Ben", 100, 1 },}; for (const auto& p : team)    printPlayer(p);
Key idea

A struct lets you treat several values as one thing. A Player is easier to pass around than three separate variables.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.