C++ Structures
A `struct` groups related variables of different types under one name, useful for representing a record like a point or a student. By default, struct members are public.
You access a struct's members using the dot `.` operator, and structs can be passed to functions, stored in arrays, or nested inside other structs.
Defining a struct
`struct Point { int x; int y; };` defines a new type. You create instances like any other variable: `Point p;` then set `p.x = 3;`.
Structs vs classes
A struct is essentially a class with public members by default, whereas a class defaults to private. Many use structs for plain data and classes for behaviour-rich objects.
struct Point { int x; int y; };
Point p = {3, 4};
std::cout << p.x << "," << p.y;3,4Struct members are accessed with dot notation.
Key points
- struct groups related fields into one type.
- Members default to public access.
- Access members with the dot operator.
- Structs can be nested and stored in arrays.
