Structs, Enums & Data Organization
Alright, let's think about something. So far, you've been storing data in separate variables — an int for age, a string for name, a double for GPA. That works fine for one student. But what happens when you need to keep track of 100 students? Are you going to create 300 separate variables? Yeah, that would be a nightmare.
This is where structs come in, and they're going to change the way you think about organizing data. A struct (short for structure) lets you bundle related variables together under one name, essentially creating your own custom data type. Think of it like a form or a record card — a student card has fields for name, age, and GPA, all on one card. You can then have a whole stack of these cards (which, in code, is just a vector of structs).
We'll also learn about enum class — a way to create variables that can only hold specific, named values. Instead of using random integers like 0, 1, 2 to represent colors (which is confusing and error-prone), you define enum class Color { Red, Green, Blue }; and write Color c = Color::Red;. Way more readable, and it prevents bugs where you accidentally assign something invalid.
| Concept | What It Solves | Example |
|---|---|---|
| Struct | Groups related data into one custom type | struct Student { string name; int age; double gpa; }; |
| Struct methods | Lets structs have their own functions | void display() const { cout << name; } |
| Enum class | Restricts a variable to a fixed set of named values | enum class Color { Red, Green, Blue }; |
| Vector of structs | Manages a collection of structured records | vector<Student> roster; |
By the end of this week, you'll be designing your own data types, storing collections of structured data in vectors, and using type-safe enumerations to make your code cleaner. And here's the exciting part — structs are the stepping stones to classes and object-oriented programming, which we'll tackle in later weeks.