C++ Structures

Grouping related data together

🏗️ What are C++ Structures?

C++ structures are user-defined data types that group related variables of different data types under a single name, making code organization easier and more readable.


// Simple structure example
struct Student {
    string name;
    int age;
    float grade;
};
                                    

Structure Concepts

📦

Definition

Create a structure template

struct Point {
    int x, y;
};
🎯

Declaration

Create structure variables

Point p1, p2;
Point p3 = {10, 20};
🔍

Access

Use dot operator to access members

p1.x = 5;
p1.y = 15;

Functions

Pass structures to functions

void display(Point p) {
    cout << p.x << ", " << p.y;
}

🔹 Basic Structure Example

A structure (struct) groups related data items of possibly different types under a single name. Define a struct with the struct keyword, a name, and member declarations inside braces. For instance, struct Student { string name; int id; double gpa; };. Create variables of this type and access members using the dot operator (.). Structures are foundational for organizing data, especially when passing grouped information to functions or building more complex data types like linked lists.

#include <iostream>
#include <string>
using namespace std;

// Define a structure
struct Person {
    string name;
    int age;
    float height;
};

int main() {
    // Create structure variable
    Person person1;
    
    // Assign values
    person1.name = "Alice";
    person1.age = 25;
    person1.height = 5.6;
    
    // Display values
    cout << "Name: " << person1.name << endl;
    cout << "Age: " << person1.age << endl;
    cout << "Height: " << person1.height << " ft" << endl;
    
    return 0;
}

Output:

Name: Alice
Age: 25
Height: 5.6 ft

🔹 Structure Initialization

Structures can be initialized in several ways: aggregate, designated, or constructor initialization. Aggregate initialization uses braces: Student s = {"Alice", 123, 3.8};. C++20 introduced designated initializers for clarity: Student s { .name="Alice", .id=123 };. You can also define constructors inside the struct for more control. Uniform initialization with {} is preferred as it prevents narrowing conversions. Proper initialization ensures members start with valid values, avoiding undefined behavior.

struct Rectangle {
    int width;
    int height;
};

int main() {
    // Method 1: Initialize during declaration
    Rectangle rect1 = {10, 20};
    
    // Method 2: Initialize after declaration
    Rectangle rect2;
    rect2.width = 15;
    rect2.height = 25;
    
    // Method 3: Uniform initialization (C++11)
    Rectangle rect3{30, 40};
    
    cout << "Rect1: " << rect1.width << "x" << rect1.height << endl;
    cout << "Rect2: " << rect2.width << "x" << rect2.height << endl;
    cout << "Rect3: " << rect3.width << "x" << rect3.height << endl;
    
    return 0;
}

Output:

Rect1: 10x20
Rect2: 15x25
Rect3: 30x40

🔹 Nested Structures

Nested structures allow a struct to contain members that are themselves structures. This is useful for modeling hierarchical data. For example, a Library struct might contain a Book struct which in turn contains an Author struct. Access nested members with multiple dot operators: lib.book.author.name. Nested structures promote organization and encapsulation. For deep nesting, consider readability—sometimes a flat design or separate namespaces might be clearer, but nested structs are ideal for logically grouped data.

struct Address {
    string street;
    string city;
    int zipCode;
};

struct Employee {
    string name;
    int id;
    Address address;  // Nested structure
};

int main() {
    Employee emp;
    emp.name = "John Doe";
    emp.id = 101;
    emp.address.street = "123 Main St";
    emp.address.city = "New York";
    emp.address.zipCode = 10001;
    
    cout << "Employee: " << emp.name << endl;
    cout << "Address: " << emp.address.street << ", " 
         << emp.address.city << " " << emp.address.zipCode << endl;
    
    return 0;
}

Output:

Employee: John Doe
Address: 123 Main St, New York 10001

🧠 Test Your Knowledge

Which operator is used to access structure members?