Structures (struct)

Structures (struct) in C++: An array holds many of the same thing: twelve temperatures, five names.

The Analogy: The Form on a Clipboard

An array holds many of the same thing: twelve temperatures, five names. A struct holds several different things that belong to one subject — like a patient admission form with name, date of birth, height and blood type on it.

You could keep four parallel arrays instead: names[i], birthDates[i], heights[i], bloodTypes[i]. It works, and it is miserable. Sort by name and everything comes apart. Insert a record and you must remember all four. A struct staples the fields together so they travel as one item, get copied as one item, and can be handed to a function as one argument.

A struct is the moment your program stops manipulating loose values and starts modelling things.


Syntax or Core Structure

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

// Definition -- note the semicolon after the closing brace
struct Book {
    std::string title;
    std::string author;
    int year{0};             // default member initialiser (C++11)
    double price{0.0};
    bool inStock{true};
};

int main() {
    // Creating instances
    Book empty;                                    // all defaults apply
    Book b1{"Dune", "Herbert", 1965, 9.99, true};  // in declaration order
    Book b2{.title = "Emma", .author = "Austen"};  // C++20 designated initialisers

    // Access with the dot operator
    std::cout << b1.title << " by " << b1.author << "\n";
    b1.price = 8.49;                               // read and write freely
    b1.inStock = false;

    // Structs are values: this is a full, independent copy
    Book copy = b1;
    copy.title = "Dune Messiah";
    std::cout << b1.title << "\n";                 // still "Dune"

    // Nesting: a struct can contain other structs
    struct Address { std::string city; std::string postcode; };
    struct Publisher { std::string name; Address office; };

    Publisher p{"Chilton", {"Philadelphia", "19106"}};
    std::cout << p.office.city << "\n";             // chain the dots

    // Collections of structs -- the normal way to hold records
    std::vector<Book> library{b1, b2};
    library.push_back({"Ubik", "Dick", 1969, 7.50, true});
    std::cout << library.size() << " books\n";

    return 0;
}

The trailing semicolon after the closing brace is required, and forgetting it produces a cascade of confusing errors on the following lines.


Technical Depth: Copies, Functions and struct-versus-class

Passing by value copies everything

void showBad(Book b)          { std::cout << b.title; }   // copies two strings!
void showGood(const Book& b)  { std::cout << b.title; }   // borrows, no copy
void discount(Book& b)        { b.price *= 0.9; }         // modifies the caller's
void makeCopy(Book b)         { b.price *= 0.9; }         // caller unaffected

Book b{"Dune", "Herbert", 1965, 9.99};
showGood(b);
discount(b);      // b.price is now 8.99
makeCopy(b);      // b.price unchanged

This is the single most consequential habit with structs. A Book contains two std::string objects, each of which allocates memory when copied. Passing by value into a function that only reads is pure waste, and it scales: a struct with a std::vector member copies the entire vector. const Type& to read, Type& to modify, by value only when you genuinely want your own copy.

Returning structs is cheap

struct Stats { double mean; int min; int max; };

Stats analyse(const std::vector<int>& data) {
    Stats s{0.0, data[0], data[0]};
    for (const int x : data) {
        s.mean += x;
        if (x < s.min) s.min = x;
        if (x > s.max) s.max = x;
    }
    s.mean /= static_cast<double>(data.size());
    return s;                        // no copy: the compiler constructs it in place
}

const Stats result = analyse({4, 8, 15, 16, 23, 42});
std::cout << result.mean << " " << result.min << "\n";

// C++17 structured bindings: unpack into named variables
const auto [mean, low, high] = analyse({1, 2, 3});
std::cout << mean << " " << low << " " << high << "\n";

Returning a struct is the clean way for a function to produce several values at once, and thanks to copy elision it costs nothing. Structured bindings then let the caller name the pieces without repeating result. everywhere.

Member functions: a struct can have behaviour

struct Rectangle {
    double width{0.0};
    double height{0.0};

    double area() const { return width * height; }        // const: does not modify
    double perimeter() const { return 2 * (width + height); }
    bool isSquare() const { return width == height; }
    void scale(double factor) { width *= factor; height *= factor; }
};

Rectangle r{3.0, 4.0};
std::cout << r.area() << "\n";      // 12
r.scale(2.0);
std::cout << r.area() << "\n";      // 48

Marking a member function const promises it will not change the object, which lets you call it on a const Rectangle&. Forget it and showGood(const Book&)-style code stops compiling. Get in the habit early: any member function that only reads should be const.

struct versus class

struct Point { int x; int y; };      // members are PUBLIC by default

class Vault {
    int secret;                     // members are PRIVATE by default
public:
    void set(int s) { secret = s; }
};

That default access level is the only language difference. Both can have member functions, constructors, and inheritance. The convention is what matters: use struct for plain aggregates of public data, class when you are enforcing invariants behind an interface. A Point with two free-floating coordinates is a struct; a BankAccount whose balance must never go negative is a class.

Comparison needs writing (before C++20)

struct Point { int x; int y; };

Point a{1, 2}, b{1, 2};
if (a == b) { }                     // ERROR: no operator== by default

// C++20: ask the compiler to generate it
struct Point2 {
    int x; int y;
    bool operator==(const Point2&) const = default;
};

// Or write it yourself for older standards
bool operator==(const Point& l, const Point& r) {
    return l.x == r.x && l.y == r.y;
}

Unlike copying and assignment, which you get for free, comparison is not generated automatically before C++20. = default on operator== compares every member in order.

Size and padding

struct Padded   { char a; int b; char c; };   // sizeof is often 12, not 6
struct Packed   { int b; char a; char c; };   // sizeof is often 8

The compiler inserts invisible padding so each member sits on an address it can access efficiently. Ordering members from largest to smallest often shrinks the struct. This rarely matters — until you have a million of them, at which point it matters a great deal.


Real World Example: A Library Catalogue

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <vector>

struct Book {
    std::string title;
    std::string author;
    int year{0};
    double price{0.0};
    int copies{0};

    // Behaviour that belongs with the data
    bool available() const { return copies > 0; }
    double stockValue() const { return price * copies; }
    std::string label() const { return title + " (" + std::to_string(year) + ")"; }
};

struct Summary {
    std::size_t titles{0};
    int totalCopies{0};
    double value{0.0};
};

// const& -- reads a vector of structs without copying a single one
Summary summarise(const std::vector<Book>& shelf) {
    Summary s;
    s.titles = shelf.size();
    for (const Book& b : shelf) {
        s.totalCopies += b.copies;
        s.value += b.stockValue();
    }
    return s;
}

// Type& -- modifies the caller's data
void restock(Book& b, int extra) { b.copies += extra; }

int main() {
    std::vector<Book> shelf{
        {"Dune",        "Herbert", 1965, 9.99, 3},
        {"Emma",        "Austen",  1815, 6.50, 0},
        {"Ubik",        "Dick",    1969, 7.25, 5},
        {"Middlemarch", "Eliot",   1871, 8.75, 2},
    };

    // Sorting a vector of structs: a lambda picks the key
    std::sort(shelf.begin(), shelf.end(),
              [](const Book& l, const Book& r) { return l.year < r.year; });

    std::cout << std::fixed << std::setprecision(2);
    for (const Book& b : shelf) {
        std::cout << std::setw(24) << std::left << b.label()
                  << std::setw(10) << std::right << b.author
                  << std::setw(8) << b.price
                  << (b.available() ? "  in stock" : "  OUT")
                  << "\n";
    }

    // Find and modify -- note Book& in the loop, not const Book&
    for (Book& b : shelf) {
        if (b.title == "Emma") { restock(b, 4); }
    }

    const Summary s = summarise(shelf);
    std::cout << "\n" << s.titles << " titles, " << s.totalCopies
              << " copies, stock value " << s.value << "\n";

    // Structured binding on a struct return value
    const auto [count, copies, value] = summarise(shelf);
    std::cout << "Average value per title: " << value / count << "\n";
    return 0;
}

Every design decision here follows from the earlier rules. available(), stockValue() and label() are const member functions, which is what lets them be called on the const Book& inside summarise. Summary exists purely so one function can return three related values without output parameters. summarise takes const std::vector<Book>& — by value it would deep-copy four books and eight strings on every call. The restocking loop uses Book& because it must write back, and restock takes Book& for the same reason. And std::sort works on structs as soon as you supply a lambda saying which member to compare — no operator< needed.


Common Mistakes

  • Forgetting the semicolon after the struct's closing brace. The errors appear on later lines.
  • Passing structs by value to functions that only read them. Copies every member, including strings and vectors.
  • Omitting const on read-only member functions, so they cannot be called on a const object.
  • Expecting == to work without defining it (before C++20's = default).
  • Using const Book& in a loop you intend to modify. It compiles until you try to assign, then the error is confusing.
  • Initialising in the wrong order. Positional braces follow declaration order; swap two same-typed members and the values land in the wrong fields silently.
  • Leaving members uninitialised. Use default member initialisers (int year{0};) so every instance starts sane.
  • Returning a reference to a local struct. It is destroyed at the closing brace.

Best Practices

  1. Default-initialise every member in the definition: double price{0.0};.
  2. const Type& to read, Type& to modify, by value only for a deliberate copy.
  3. Mark every non-mutating member function const.
  4. Use struct for public aggregates, class when invariants must be protected.
  5. Prefer returning a struct over multiple output parameters, and unpack it with structured bindings.
  6. Use C++20 designated initialisers ({.title = "Emma"}) when a struct has many fields — it is self-documenting and immune to reordering.
  7. Keep structs focused. Ten-plus unrelated members usually means two structs are hiding inside one.

Practice Exercises

  1. Contact book: Define a Contact struct with name, phone, email and a bool favourite. Hold a std::vector<Contact>, add entries, list them, and print only the favourites.
  2. Nested inventory: Define Dimensions { double l, w, h; } with a const volume() method, embed it in a Product struct, and report the total shipping volume of a vector of products.
  3. Sort three ways: Take the library example and sort it by title, then by price descending, then by availability. Write each comparator as a lambda and explain why std::sort needs one.