Comp 11

Heterogeneous Aggregate Storage

Review

Introducing struct

A struct is an aggregate data structure, like an array: it keeps values together. However, a struct can store elements of different types – it is thus heterogeneous. Also, its elements are named – C++ calls them member variables.

Just as there are lots of real-world examples of arrays, there are many examples of heterogeneous collections: A wallet might contain paper money, coins, pictures, credit cards. A jewelry box usually has different sized compartments for earings, necklaces, pins, etc. A silverware tray has different slots for forks, knives, spoons.

We can model many such collections using separate variables (if there is only one wallet, jewelry box, silverware tray, ...) or parallel arrays (if we have a collection of such things). But both cases fail to model the notion that the contents of a particular wallet all belong together.

Example: Tracking Course Information

Let's imagine the following situation. You'd like to keep track of your course information. Each course will have the following information associated with it:

Clearly, a homogeneous structure like an array does not suit our needs. However, a struct would be perfect!

struct-demo.cpp.

Miscellaneous struct information

Allocation and initialization.

To create a variable of a structure type (which will allocate enough memory to hold values for all the members), you can do either of the following:

But don't mix the two forms.

You may optionally initialize the members of a structure by giving their values in the order the members were declared:

Accessing member variables

You can access the members of struct using dot notation:

Assignment

Other information

  • What can go inside a struct? Anything!
  • Combining struct with array
  • How does a struct differ from a class?
  • Practice Exercise

    You're writing a trip planning application, and you want to include airline flights. Define a struct to model airline flights (what are the elements). Imagine you want to be able to search for a particular flight — what do you need?

    Mark A. Sheldon (msheldon@cs.tufts.edu)
    Last Modified 2021-Jan-12