C++ ยท Chapter 22 of 49

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.

Example 1 (cpp)
struct Point { int x; int y; };
Point p = {3, 4};
std::cout << p.x << "," << p.y;
Output
3,4

Struct 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.
๐Ÿ’ก Note: In modern C++, structs can also have constructors and methods, blurring the line with classes.

๐Ÿ“ Quick Quiz

1. What operator accesses struct members?

2. By default, struct members are:

3. A struct is best used for: