User-Defined Types: Structures and Unions in C++
The Lunchbox Analogy π±
Imagine you have a lunchbox. Inside, you can organize different foods in separate compartments: a sandwich here, an apple there, and some cookies in another spot. Each compartment holds something different, but they all travel together as ONE lunchbox.
Thatβs exactly what a Structure is in C++!
Now imagine a different lunchboxβa magical one. It only has ONE compartment, but that compartment can transform to hold EITHER a sandwich OR an apple OR cookiesβbut only ONE thing at a time.
Thatβs a Union!
Letβs dive into this delicious journey of organizing data!
Part 1: Structures (struct)
What is a Structure?
A structure is like a custom container you design yourself. You decide what goes inside and give each compartment a name.
Real Life Example:
- A Student ID Card has: Name, Age, Roll Number, Grade
- All these pieces of info travel together as ONE card
- Thatβs a structure!
Creating Your First Structure
struct Student {
string name;
int age;
int rollNumber;
char grade;
};
Think of this as designing your lunchbox blueprint:
name= compartment for the sandwichage= compartment for the applerollNumber= compartment for cookiesgrade= compartment for juice
Using a Structure
Student alice; // Create a lunchbox
alice.name = "Alice"; // Put sandwich in
alice.age = 10; // Put apple in
alice.rollNumber = 42; // Put cookies in
alice.grade = 'A'; // Put juice in
The dot (.) is like opening a specific compartment!
Why Use Structures?
Without structures, youβd carry everything separately:
// Messy way - like carrying food
// in separate bags
string name1 = "Alice";
int age1 = 10;
string name2 = "Bob";
int age2 = 11;
// Gets confusing fast!
With structures, everything is organized:
// Clean way - one lunchbox per person
Student alice;
Student bob;
// Much better!
Structure Initialization
Method 1: One by one
Student s1;
s1.name = "Emma";
s1.age = 9;
Method 2: All at once (like packing lunch the night before)
Student s2 = {"Liam", 10, 101, 'B'};
Method 3: Named initialization (C++20)
Student s3 = {
.name = "Noah",
.age = 11,
.rollNumber = 102,
.grade = 'A'
};
Structures with Functions
Structures can travel to functions just like regular variables!
void printStudent(Student s) {
cout << "Name: " << s.name;
cout << " Age: " << s.age;
}
// Using it:
Student myStudent = {"Zoe", 8, 55, 'A'};
printStudent(myStudent);
Nested Structures
A lunchbox inside a lunchbox? Yes!
struct Date {
int day;
int month;
int year;
};
struct Student {
string name;
Date birthday; // Structure inside!
};
Student kid;
kid.name = "Max";
kid.birthday.day = 15;
kid.birthday.month = 6;
kid.birthday.year = 2014;
Array of Structures
Many lunchboxes in a row!
Student classroom[30]; // 30 students!
classroom[0].name = "First Student";
classroom[1].name = "Second Student";
Part 2: Unions
What is a Union?
Remember the magical transforming compartment? A union is exactly thatβONE storage space that can hold different types of data, but only ONE at a time.
Real Life Example:
- A parking spot can hold a car OR a motorcycle OR a bicycle
- But only ONE vehicle at a time!
- Thatβs a union!
Creating a Union
union Container {
int number;
float decimal;
char letter;
};
The Key Difference from Structures
Structure (struct): Union:
βββββββββββ¬ββββββββββ βββββββββββ
β number β decimal β β number β
βββββββββββΌββββββββββ€ OR β decimal β
β letter β (empty) β β letter β
βββββββββββ΄ββββββββββ βββββββββββ
All compartments exist! ONE space, shared!
Memory Magic
Structure: Each member gets its own space
struct S {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};
// Total: ~9+ bytes
Union: All members SHARE the same space
union U {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};
// Total: 4 bytes (size of largest)
Using a Union
union Value {
int whole;
float decimal;
};
Value v;
v.whole = 42; // Store an integer
cout << v.whole; // Works! Shows 42
v.decimal = 3.14; // Now store a float
// v.whole is now GARBAGE!
// Only v.decimal is valid
Warning: Only the LAST thing you put in is valid!
When to Use Unions?
- Saving Memory - When you have limited space
- Either/Or Data - When something can be one type OR another
- Low-level Programming - Working close to hardware
Practical Union Example
union IPAddress {
unsigned int full;
unsigned char parts[4];
};
IPAddress ip;
ip.full = 3232235777; // One number
// Access individual parts!
cout << (int)ip.parts[0]; // 192
cout << (int)ip.parts[1]; // 168
cout << (int)ip.parts[2]; // 1
cout << (int)ip.parts[3]; // 1
// That's 192.168.1.1!
Structures vs Unions: Quick Comparison
graph TD A["Need to store data?"] --> B{Multiple values<br>at SAME time?} B -->|Yes| C["Use STRUCT"] B -->|No, only one| D["Use UNION"] C --> E["Each member<br>has own space"] D --> F["All members<br>share space"]
| Feature | Structure | Union |
|---|---|---|
| Memory | Sum of all | Size of largest |
| Access | All members anytime | Only last assigned |
| Use case | Group related data | Save memory |
| Keyword | struct |
union |
Fun Challenge: Build a Game Character!
struct Position {
int x;
int y;
};
struct Character {
string name;
int health;
Position location;
};
Character hero;
hero.name = "Knight";
hero.health = 100;
hero.location.x = 0;
hero.location.y = 0;
You just created a game character with a name, health bar, and position on the mapβall packed neatly in one structure!
Key Takeaways
- Structures = Multiple compartments, all available at once
- Unions = One compartment that transforms, only one thing at a time
- Use dot notation (
.) to access members - Structures are for grouping related data
- Unions are for saving memory when you need either/or storage
You Did It! π
You now understand how to create your own custom data types in C++! Structures help you organize related information together, while unions help you save memory when you only need one value at a time.
Think of it this way:
- struct = A lunchbox with compartments
- union = A magical single compartment that shape-shifts
Now go build something amazing with your new knowledge! π
