Structures and Unions

Back

Loading concept...

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 sandwich
  • age = compartment for the apple
  • rollNumber = compartment for cookies
  • grade = 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?

  1. Saving Memory - When you have limited space
  2. Either/Or Data - When something can be one type OR another
  3. 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&lt;br&gt;has own space"] D --> F["All members&lt;br&gt;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

  1. Structures = Multiple compartments, all available at once
  2. Unions = One compartment that transforms, only one thing at a time
  3. Use dot notation (.) to access members
  4. Structures are for grouping related data
  5. 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! πŸš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.