C++ Notes: Structs


In addition to the simple data types (int, char, double, ...) there are composite data types which combine more than one data element. Arrays store elements of the same type, which are accessed by subscript, eg, a[i]. Structs (also called records, or classes) group elements which don't need to all be the same type, and are accessed by field (member) name, eg, r.name.

Struct Declaration defines a new Type

The most common struct declaration in C++ is to define a new type. This example represents information about products.
struct Product {
    char mfg_id[4];    // 4 char code for the manufacturer.
    char prod_id[8];   // 8-char code for the product
    int  price;        // price of the product in dollars.
    int  qty_on_hand;  // quantity on hand in inventory
This defines a new type, Product. The order of the fields is generally not important. Don't forget the semicolon after the right brace. The convention is to capitalize the first letter in any new type name.

Declaring struct variables

The new struct type can now be used to declare variables. For example,
Product widget;

Accessing the fields of a struct

Access the fields of a struct by using the "." operator followed by the name of the field.
widget.price = 200;
widget.qty_on_hand = 17;
strcpy(widget.mfg_id, "IBM");
strcpy(widget.prod_id, "Thingee");

Like database records

Structs are like database records - a row in a table, where the field names are like the column names.

Related Pages