Skip to main content

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 strings and an enrollmentDate which is a Date.” To diagram what a Student variable named s1 might look like, we would draw something like this:
A student struct that contains a date struct
Figure 15.6.1.
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:
Listing 15.6.2.
Some things to note:
  • Student s1’s enrollmentDate is initialized using Date d1. 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 use s1.enrollmentDate.month which specifies a single int. That the compiler knows what to do with.
  • Student s2’s enrollmentDate 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 the printStudent function. It uses s.enrollmentDate to access the entire Date struct for that student and pass it to printDate.
The memory diagram for the state at the end of main would look something like this:
A Date d1 and Students s1 and s2
Figure 15.6.3.

Checkpoint 15.6.1.

Checkpoint 15.6.2.

Hint.
You should use the list syntax - { } - to specify the date.
You have attempted of activities on this page.