bhylu.com

Advertisements

C++ Structures

Model one delivery stop with named fields and iterate a collection of complete records.

How it works

A struct groups related fields into one type. Unlike parallel arrays, one index selects a complete stop, keeping its name and parcel count together. A simple aggregate with public fields is appropriate when it has no hidden invariant beyond its documented data meaning. class and struct differ mainly in default access and inheritance access; both can define methods and constructors. Use a class with controlled operations when invalid combinations must be prevented at every mutation.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror records.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · records.cpp

#include <iostream>
#include <string>
#include <vector>

struct Stop {
    std::string name;
    int parcels{};
};

int main() {
    std::vector<Stop> stops{{"Quay", 3}, {"Market", 5}};
    for (const auto& stop : stops) { std::cout << stop.name << ": " << stop.parcels << '\n'; }
}

Expected result

Quay: 3
Market: 5

The range variable is a const reference, avoiding a copy of each string while preventing modification through that view. Each string owns its text, and the vector owns its Stop objects. These automatic owners clean up when they leave scope. A nested structure can represent an address or time window without flattening every field into the outer record.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.