Structs

An enum holds one value from a fixed list. Often you need a type that holds several values at once. A product in a shop has a name, a price and a stock count. You could keep these in three separate variables, but they belong together. A struct lets you create your own type that groups related values into one.

#include <iostream>
#include <string>
using namespace std;

struct Product {
    string name;
    double price;
    int stock;
};

int main() {
    Product soap = {"soap", 2.5, 40};
    Product tea = {"tea", 4.0, 12};
    cout << soap.name << " costs " << soap.price << "\n";
    tea.stock = tea.stock - 2;
    cout << tea.stock << " boxes of tea left" << "\n";
    return 0;
}

Output:

soap costs 2.5
10 boxes of tea left

The struct block creates a new type called Product. The variables inside it (name, price and stock) are its members. The block itself does not create any product yet. It only describes what a product looks like.

Product soap = {"soap", 2.5, 40}; creates a real product. The values in the braces fill the members in the same order they are written in the struct. You reach each member with a dot, like soap.name. A member works like a normal variable: you can print it, change it, or use it in a calculation.

Each product has its own copy of the members. Changing tea.stock did not touch soap.stock.

Note the semicolon after the closing brace of the struct. It is easy to forget, and then the program does not compile:

#include <iostream>
#include <string>
using namespace std;

struct Product {
    string name;
    double price;
    int stock;
}

int main() {
    Product soap = {"soap", 2.5, 40};
    cout << soap.name << "\n";
    return 0;
}

Output:

main.cpp:9:2: error: expected ‘;’ after struct definition
    9 | }
      |  ^
      |  ;

Using a struct like any other type

Product is now a type, just like int or string. A function can take a Product as a parameter, and a vector can hold many products:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Product {
    string name;
    double price;
    int stock;
};

void show(Product p) {
    cout << p.name << ": " << p.stock << "\n";
}

int main() {
    vector<Product> shop = {
        {"soap", 2.5, 40},
        {"tea", 4.0, 12}
    };
    for (Product p : shop) {
        show(p);
    }
    return 0;
}

Output:

soap: 40
tea: 12

Passing one Product is simpler than passing three separate values, and you cannot mix up their order.

A struct groups data, but it does not protect it. tea.stock = -5; would compile without any complaint. The next lessons show classes, which add functions that work on the data and can protect it.

In the exercise, define a Book struct with a title and a number of pages.