Section 15.6 Compound Structures
Once we have defined a structures, we can use it to define other structures. For example, given this
date
structure:
struct Date {
int month;
int day;
int year;
};
We can define a new structure representing a student that includes a date:
struct Student {
string name;
string email;
Date enrollmentDate;
};
This says that βa
Student
as a name
and email
that are string
s and an enrollmentDate
which is a Date
.β To diagram what a Student
variable named s1
might look like, we would draw something like this:
In this diagram, the
Student
struct is shown as a box with three parts. Two parts are the name
and email
strings. The third part is a Date
struct, which is itself a box with three parts. When we say s1.enrollmentDate
we are talking about the entire date struct that is a part of that student. To talk about the members of that struct, we need to use the dot operator again. For example, to access the month of a student
βs enrollment date, we would write s1.enrollmentDate.month
.
This program demonstrates creating and using our compound data type:
Some things to note:
-
Student
s1
βsenrollmentDate
is initialized using Dated1
. It gets a copy of that date - 9/14/2023. -
Lines 41-45 print student s1βs members one by one. Note that printing the date requires accessing each part individually. We canβt just say
cout << s1.enrollmentDate
as the compiler doesnβt know how to print a Date. We need uses1.enrollmentDate.month
which specifies a single int. That the compiler knows what to do with. -
Student
s2
βsenrollmentDate
is initialized using an initializer list (lines 48-52). So we have a list for the date inside the list for the student. -
We print
s2
using theprintStudent
function. It usess.enrollmentDate
to access the entireDate
struct for that student and pass it toprintDate
.
The memory diagram for the state at the end of
main
would look something like this:
Checkpoint 15.6.2.
You have attempted of activities on this page.