COMP15 Spring 2018
Data Structures
Last updated January 09, 2018 14:58:43 EST

General Information Syllabus Schedule Homeworks and Projects
 Labs Resources  

Structs should be used for passive objects that carry data. They're similar to classes in that we use them to wrap different data types into one piece of information. We also define a struct once and then create multiple instances of it.

In COMP15, we'll tend to use structs to be the elements of a data structure. We know that data structures such as arrays require every element to be of the same type. We've made arrays of primitves (like ints) and arrays of objects (like Cards). Sometimes we want something more complex than a primitive but not as involved as an object. For example, you might want to have an array where each element is an int and a double. We would define a struct that wraps an int and a double together and boom -- that's our new data type.

Structs should be nothing but data, which is public, and perform absolutely no functionality. Structs can have functions, but if you need functions plus data, write a class instead.

Here is an example of a struct:

struct Latte {
 char size;
 bool extra_shot;
 string milk_type;
 bool foam;

And here's how I would create a struct instance (just like instantiating an object) and initialize its variables:

Latte laneys_coffee;
laneys_coffee.size = 'L';
laneys_coffee.extra_shot = false;
laneys_coffee.milk_type = "almond";
laneys_coffee.foam = false;

And here's how I would make an array of Lattes:

Latte drinks[50];

Laney Strange
Last updated January 09, 2018 14:58:43 EST