Structures (struct)

In C++, a structure (struct) lets you group different pieces of data together under one name. You can think of it like a custom data type that you design yourself.

What Is a struct?

A struct groups related variables (called members) of possibly different types.

Syntax

struct TypeName {
    member_type1 member_name1;
    member_type2 member_name2;
    // ...
};
  • TypeName → the name of your new type
  • Inside { } → the members (variables) that belong to this type

Example: A product Structure

#include <iostream>
using namespace std;

struct product {
    int weight;     // in grams
    double price;   // in riyals
};

int main() {
    product apple;
    product banana, melon;

    apple.weight = 150;
    apple.price  = 1.99;

    banana.weight = 120;
    banana.price  = 0.99;

    cout << "Apple: "  << apple.weight  << " g, " << apple.price << " SAR" << endl;
    cout << "Banana: " << banana.weight << " g, " << banana.price << " SAR" << endl;
}

Accessing Members

Use the dot operator .:

  • apple.weightint
  • apple.pricedouble

You can read/write them just like normal variables.

Declaring Objects Right After the struct

You can declare variables at the end of the struct definition:

struct product {
    int weight;
    double price;
} apple, banana, melon;

Here:

  • product is the type name
  • apple, banana, melon are variables (objects) of that type