Ch2.21: struct
Overview
A struct lets you group several values together under a single name.
In this chapter, we define the simplest kind of struct:
an aggregate. An aggregate contains only data members and has no hidden behavior.
You will learn:
- how to define a
structaggregate - how to create an object of that type
- how to read and write its members
- how aggregate initialization works
1. Defining a struct aggregate
A struct with only data members is an aggregate.
struct Point {
int x;
int y;
}; // ← do not forget this semicolon
The semicolon is required. Forgetting it is a very common beginner mistake.
This defines a new type named Point with two members:
x and y.
2. Creating a struct object
You can create a Point using brace initialization:
Point p{3, 4};
This sets p.x = 3 and p.y = 4.
3. Accessing and modifying members
Use the dot operator (.) to read or write members.
Point p{3, 4};
print("x=", p.x, " y=", p.y);
p.x = 10;
p.y = 20;
print("x=", p.x, " y=", p.y);
Each member behaves like a normal variable.
4. Designated initialization
Aggregates support designated initializers:
Point a{.x = 1, .y = 2};
This sets the members by name.
5. What we are not covering yet
In this chapter, we intentionally avoid:
classpublic/private- member functions
- constructors
- methods
- containers
- loops
A struct aggregate is simply a group of values with no hidden behavior.
Key takeaways
- A
structwith only data members is an aggregate. - Aggregates support simple brace initialization.
- Members are accessed using
.. - Aggregates contain no hidden behavior.