Arrays of Structures or Classes

Arrays of structures or classes allow you to organize complex data in a way that makes it easy to manage and access. Structures (struct) and classes (class) in C++ can have multiple data members and member functions, and you can create arrays of these objects to store collections of related data.

Why Use Arrays of Structures or Classes?

When working with related pieces of data, such as information about students, employees, products, or customers, an array of structures or classes is an ideal way to organize and handle these records. You can store multiple objects in an array and access them using array indexing.

Defining Arrays of Structures

Consider a structure that holds information about a student, such as their name, age, and grade:

#include <iostream>
#include <string>

// Define a structure for Student
struct Student {
    std::string name;
    int age;
    float grade;
};

int main() {
    // Create an array of Student structures
    Student students[3] = {
        {"Alice", 20, 85.5},
        {"Bob", 21, 90.0},
        {"Charlie", 22, 88.0}
    };

    // Access and display the elements of the array
    for (int i = 0; i < 3; i++) {
        std::cout << "Name: " << students[i].name << ", Age: " << students[i].age << ", Grade: " << students[i].grade << std::endl;
    }

    return 0;
}

In this example:

  • A Student structure is defined with three data members: name, age, and grade.
  • An array of three Student structures is created and initialized.
  • A for loop is used to iterate over the array and print each student’s details.

Arrays of Classes

You can also create arrays of class objects. The syntax and usage are similar to arrays of structures. Classes in C++ provide the added advantage of encapsulation and member functions.

For example, suppose we define a Book class:

#include <iostream>
#include <string>

class Book {
public:
    std::string title;
    std::string author;
    int year;

    // Constructor to initialize Book
    Book(std::string t, std::string a, int y) : title(t), author(a), year(y) {}

    // Member function to display book details
    void display() const {
        std::cout << "Title: " << title << ", Author: " << author << ", Year: " << year << std::endl;
    }
};

int main() {
    // Create an array of Book objects
    Book books[2] = {
        Book("The Catcher in the Rye", "J.D. Salinger", 1951),
        Book("1984", "George Orwell", 1949)
    };

    // Access and display each book in the array
    for (int i = 0; i < 2; i++) {
        books[i].display();
    }

    return 0;
}

In this example:

  • A Book class is defined with three data members: title, author, and year.
  • A constructor is provided to initialize these data members.
  • A display() member function is defined to output book details.
  • An array of Book objects is created and initialized using the constructor.

Key Points to Remember

  • Structures and Classes: Arrays can store both struct and class objects. Structures are often used for plain data storage, while classes provide additional functionality and encapsulation.
  • Accessing Members: You can access members of an object in an array using dot notation (e.g., students[i].name).
  • Initialization: You can initialize arrays of objects at the time of declaration, either by calling constructors (for classes) or directly assigning values (for structures).
  • Member Functions: When dealing with arrays of classes, you can use member functions to manipulate or access object data.

Use Cases for Arrays of Structures or Classes

  • Managing Records: Store data for students, employees, books, customers, etc.
  • Game Development: Use an array of objects to store game entities, players, enemies, or objects.
  • Data Analysis: Store data points or records for statistical or computational processing.

Example of Using Arrays with Structures and Classes

1. Structure Example:

#include <iostream>

struct Employee {
    int id;
    std::string name;
    float salary;
};

int main() {
    Employee employees[2] = {
        {101, "John Doe", 50000.0},
        {102, "Jane Smith", 55000.0}
    };

    for (int i = 0; i < 2; i++) {
        std::cout << "ID: " << employees[i].id << ", Name: " << employees[i].name << ", Salary: $" << employees[i].salary << std::endl;
    }

    return 0;
}

2. Class Example:

#include <iostream>

class Product {
public:
    int productId;
    std::string productName;
    double price;

    // Constructor to initialize Product
    Product(int id, std::string name, double p) : productId(id), productName(name), price(p) {}

    // Function to print product details
    void printDetails() const {
        std::cout << "Product ID: " << productId << ", Product Name: " << productName << ", Price: $" << price << std::endl;
    }
};

int main() {
    Product products[3] = {
        Product(1, "Laptop", 1200.99),
        Product(2, "Smartphone", 699.99),
        Product(3, "Tablet", 299.99)
    };

    for (int i = 0; i < 3; i++) {
        products[i].printDetails();
    }

    return 0;
}