Coming Soon

This lesson is currently being developed

Introduction to structs members and member selection

Group related data together with structures.

Compound Types: Enums and Structs
Chapter
Beginner
Difficulty
45min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

13.7 — Introduction to structs, members and member selection

In this lesson, you'll learn about structures (structs) - a way to group related variables together into a single unit, and how to access their members.

What are structs?

A struct (short for structure) is a program-defined type that allows you to group related variables together. Think of a struct like a container that holds multiple pieces of related information.

For example, instead of storing a person's information in separate variables:

std::string firstName = "Alice";
std::string lastName = "Johnson";
int age = 25;
double height = 5.6;

You can group them together in a struct:

struct Person
{
    std::string firstName;
    std::string lastName;
    int age;
    double height;
};

Defining a struct

Here's the basic syntax for defining a struct:

struct struct_name
{
    data_type member1;
    data_type member2;
    // ... more members
};

The variables inside a struct are called members (or member variables).

Let's create a struct to represent a point in 2D space:

#include <iostream>

struct Point
{
    int x;  // member variable
    int y;  // member variable
};

int main()
{
    // We'll use this struct in the next example
    return 0;
}

Creating struct objects

Once you've defined a struct, you can create objects (instances) of that struct type:

#include <iostream>

struct Point
{
    int x;
    int y;
};

int main()
{
    Point p1;        // Create a Point object named p1
    Point p2;        // Create another Point object named p2
    Point origin;    // Create a Point object named origin
    
    std::cout << "Created three Point objects" << std::endl;
    
    return 0;
}

Output:

Created three Point objects

Member selection with the dot operator

To access the members of a struct, you use the member selection operator (the dot .):

object_name.member_name

Here's how to access and modify struct members:

#include <iostream>

struct Point
{
    int x;
    int y;
};

int main()
{
    Point p1;
    
    // Access and assign values to members
    p1.x = 3;
    p1.y = 5;
    
    // Access and print member values
    std::cout << "Point p1: (" << p1.x << ", " << p1.y << ")" << std::endl;
    
    // You can also use members in calculations
    int sum = p1.x + p1.y;
    std::cout << "Sum of coordinates: " << sum << std::endl;
    
    return 0;
}

Output:

Point p1: (3, 5)
Sum of coordinates: 8

A more complex struct example

Let's create a struct to represent a student:

#include <iostream>
#include <string>

struct Student
{
    std::string name;
    int age;
    double gpa;
    bool isEnrolled;
};

int main()
{
    Student alice;
    
    // Assign values to all members
    alice.name = "Alice Johnson";
    alice.age = 20;
    alice.gpa = 3.75;
    alice.isEnrolled = true;
    
    // Print student information
    std::cout << "Student Information:" << std::endl;
    std::cout << "Name: " << alice.name << std::endl;
    std::cout << "Age: " << alice.age << std::endl;
    std::cout << "GPA: " << alice.gpa << std::endl;
    std::cout << "Enrolled: " << (alice.isEnrolled ? "Yes" : "No") << std::endl;
    
    return 0;
}

Output:

Student Information:
Name: Alice Johnson
Age: 20
GPA: 3.75
Enrolled: Yes

Working with multiple struct objects

You can create multiple objects of the same struct type:

#include <iostream>
#include <string>

struct Rectangle
{
    double width;
    double height;
    std::string color;
};

double calculateArea(const Rectangle& rect)
{
    return rect.width * rect.height;
}

int main()
{
    Rectangle rect1;
    rect1.width = 5.0;
    rect1.height = 3.0;
    rect1.color = "red";
    
    Rectangle rect2;
    rect2.width = 4.0;
    rect2.height = 6.0;
    rect2.color = "blue";
    
    std::cout << "Rectangle 1: " << rect1.width << "x" << rect1.height 
              << " (" << rect1.color << ")" << std::endl;
    std::cout << "Area: " << calculateArea(rect1) << std::endl;
    
    std::cout << "\nRectangle 2: " << rect2.width << "x" << rect2.height 
              << " (" << rect2.color << ")" << std::endl;
    std::cout << "Area: " << calculateArea(rect2) << std::endl;
    
    return 0;
}

Output:

Rectangle 1: 5x3 (red)
Area: 15

Rectangle 2: 4x6 (blue)
Area: 24

Structs with different member types

Structs can contain members of any type, including other structs:

#include <iostream>
#include <string>

struct Address
{
    std::string street;
    std::string city;
    std::string state;
    int zipCode;
};

struct Person
{
    std::string name;
    int age;
    Address homeAddress;  // struct member containing another struct
};

int main()
{
    Person john;
    
    // Assign values to simple members
    john.name = "John Smith";
    john.age = 35;
    
    // Assign values to nested struct members
    john.homeAddress.street = "123 Main St";
    john.homeAddress.city = "Springfield";
    john.homeAddress.state = "IL";
    john.homeAddress.zipCode = 62701;
    
    // Print person information
    std::cout << "Name: " << john.name << std::endl;
    std::cout << "Age: " << john.age << std::endl;
    std::cout << "Address: " << john.homeAddress.street << std::endl;
    std::cout << "         " << john.homeAddress.city << ", " 
              << john.homeAddress.state << " " << john.homeAddress.zipCode << std::endl;
    
    return 0;
}

Output:

Name: John Smith
Age: 35
Address: 123 Main St
         Springfield, IL 62701

Structs in functions

You can pass structs to functions and return them from functions:

#include <iostream>
#include <string>

struct Circle
{
    double radius;
    std::string color;
};

double calculateCircleArea(const Circle& circle)
{
    return 3.14159 * circle.radius * circle.radius;
}

void printCircle(const Circle& circle)
{
    std::cout << "Circle: radius = " << circle.radius 
              << ", color = " << circle.color 
              << ", area = " << calculateCircleArea(circle) << std::endl;
}

Circle createCircle(double radius, const std::string& color)
{
    Circle newCircle;
    newCircle.radius = radius;
    newCircle.color = color;
    return newCircle;
}

int main()
{
    Circle c1 = createCircle(5.0, "red");
    Circle c2 = createCircle(3.0, "blue");
    
    printCircle(c1);
    printCircle(c2);
    
    return 0;
}

Output:

Circle: radius = 5, color = red, area = 78.5397
Circle: radius = 3, color = blue, area = 28.2743

Comparing structs

You cannot directly compare structs with comparison operators like == or !=. You need to compare individual members:

#include <iostream>

struct Point
{
    int x;
    int y;
};

bool arePointsEqual(const Point& p1, const Point& p2)
{
    return (p1.x == p2.x) && (p1.y == p2.y);
}

int main()
{
    Point p1{3, 5};
    Point p2{3, 5};
    Point p3{2, 7};
    
    // This won't work:
    // if (p1 == p2) { }  // ERROR: no operator== for Point
    
    // Use a comparison function instead:
    if (arePointsEqual(p1, p2))
    {
        std::cout << "p1 and p2 are equal" << std::endl;
    }
    
    if (!arePointsEqual(p1, p3))
    {
        std::cout << "p1 and p3 are different" << std::endl;
    }
    
    return 0;
}

Output:

p1 and p2 are equal
p1 and p3 are different

Practical example: Inventory system

Here's a more practical example showing how structs can be used in a simple inventory system:

#include <iostream>
#include <string>

struct Product
{
    int id;
    std::string name;
    double price;
    int quantity;
    bool inStock;
};

void printProduct(const Product& product)
{
    std::cout << "ID: " << product.id << std::endl;
    std::cout << "Name: " << product.name << std::endl;
    std::cout << "Price: $" << product.price << std::endl;
    std::cout << "Quantity: " << product.quantity << std::endl;
    std::cout << "In Stock: " << (product.inStock ? "Yes" : "No") << std::endl;
    std::cout << "Total Value: $" << (product.price * product.quantity) << std::endl;
    std::cout << "---" << std::endl;
}

bool sellProduct(Product& product, int amount)
{
    if (product.quantity >= amount && product.inStock)
    {
        product.quantity -= amount;
        if (product.quantity == 0)
        {
            product.inStock = false;
        }
        return true;  // Sale successful
    }
    return false;  // Sale failed
}

int main()
{
    Product laptop;
    laptop.id = 1001;
    laptop.name = "Gaming Laptop";
    laptop.price = 1299.99;
    laptop.quantity = 5;
    laptop.inStock = true;
    
    Product mouse;
    mouse.id = 1002;
    mouse.name = "Wireless Mouse";
    mouse.price = 29.99;
    mouse.quantity = 0;
    mouse.inStock = false;
    
    std::cout << "Initial inventory:" << std::endl;
    printProduct(laptop);
    printProduct(mouse);
    
    // Try to sell some laptops
    if (sellProduct(laptop, 2))
    {
        std::cout << "Successfully sold 2 laptops!" << std::endl;
    }
    
    // Try to sell a mouse (should fail - out of stock)
    if (!sellProduct(mouse, 1))
    {
        std::cout << "Cannot sell mouse - out of stock!" << std::endl;
    }
    
    std::cout << "\nUpdated inventory:" << std::endl;
    printProduct(laptop);
    
    return 0;
}

Output:

Initial inventory:
ID: 1001
Name: Gaming Laptop
Price: $1299.99
Quantity: 5
In Stock: Yes
Total Value: $6499.95
---
ID: 1002
Name: Wireless Mouse
Price: $29.99
Quantity: 0
In Stock: No
Total Value: $0
---
Successfully sold 2 laptops!
Cannot sell mouse - out of stock!

Updated inventory:
ID: 1001
Name: Gaming Laptop
Price: $1299.99
Quantity: 3
In Stock: Yes
Total Value: $3899.97
---

Best practices for structs

1. Use meaningful names

// Good
struct StudentRecord
{
    std::string fullName;
    int studentId;
    double gradePointAverage;
};

// Less clear
struct Data
{
    std::string n;
    int id;
    double gpa;
};

2. Group related data together

// Good: related data grouped together
struct BankAccount
{
    std::string accountNumber;
    double balance;
    std::string ownerName;
};

// Less ideal: unrelated data mixed together
struct MixedData
{
    std::string accountNumber;
    int playerScore;        // Unrelated to banking
    double balance;
    std::string gameLevel;  // Unrelated to banking
};

3. Keep structs simple and focused

// Good: focused struct
struct Point2D
{
    double x;
    double y;
};

// Good: focused struct
struct Color
{
    int red;
    int green;
    int blue;
};

Key concepts to remember

  1. Structs group related variables together into a single unit.

  2. Use the dot operator (.) to access struct members.

  3. Each struct object has its own copy of all member variables.

  4. Structs can contain members of any type, including other structs.

  5. You cannot directly compare structs - you must compare individual members.

  6. Structs can be passed to and returned from functions like any other type.

Summary

Structs are a powerful way to organize related data together. They help make your code more organized, readable, and maintainable by grouping related information into logical units. You access struct members using the dot operator, and each struct object maintains its own copy of the member data. Structs form the foundation for more advanced concepts like classes and are essential for modeling real-world entities in your programs.

Quiz

  1. What is a struct and why is it useful?
  2. How do you access a member of a struct object?
  3. Can a struct contain members of different data types?
  4. Can you directly compare two struct objects using ==? Why or why not?
  5. What happens when you create multiple objects of the same struct type?

Practice exercises

Try creating these structs and working with them:

  1. Create a Book struct with title, author, pages, and price. Create several book objects and print their information.
  2. Create a Temperature struct with Celsius and Fahrenheit values. Write functions to convert between them.
  3. Create a Car struct with make, model, year, and mileage. Create an array of cars and find the oldest car.
  4. Create a Time struct with hours, minutes, and seconds. Write functions to add and subtract time values.

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion