C++ Array of Objects

Introduction

In C++, an array of objects allows you to manage and manipulate multiple instances of a class efficiently. By creating an array of objects, you can easily access and modify the attributes and behaviors of each object within the array. This approach is particularly useful in scenarios where you need to handle collections of related entities, such as students, employees, or products.

Defining a Class and Creating an Array of Objects

To define an array of objects, you first create a class with the necessary members and member functions. Then, you create an array of that class type.

Example: Defining a Class and Creating an Array

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;
    double grade;

    // Constructor
    Student(string n, int a, double g) : name(n), age(a), grade(g) {}

    // Member function to display student details
    void display() {
        cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
    }
};

int main() {
    // Create an array of Student objects
    Student students[3] = {
        Student("Aarav", 20, 88.5),
        Student("Siya", 21, 92.0),
        Student("Rohan", 19, 75.0)
    };

    // Print student data
    for (int i = 0; i < 3; i++) {
        students[i].display();
    }

    return 0;
}

Output

Name: Aarav, Age: 20, Grade: 88.5
Name: Siya, Age: 21, Grade: 92
Name: Rohan, Age: 19, Grade: 75

Explanation

  • The Student class is defined with name, age, and grade members and a constructor to initialize these members.
  • A member function display is defined to print the student’s details.
  • An array of Student objects, students, is created and initialized with data for three students.
  • A loop iterates through the array, calling the display function for each student to print their details.

Practical Examples

Example 1: Calculating the Average Grade

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;
    double grade;

    Student(string n, int a, double g) : name(n), age(a), grade(g) {}

    void display() {
        cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
    }
};

double calculateAverageGrade(Student students[], int size) {
    double total = 0;
    for (int i = 0; i < size; i++) {
        total += students[i].grade;
    }
    return total / size;
}

int main() {
    Student students[3] = {
        Student("Aarav", 20, 88.5),
        Student("Siya", 21, 92.0),
        Student("Rohan", 19, 75.0)
    };

    int size = 3;
    double averageGrade = calculateAverageGrade(students, size);

    cout << "Average Grade: " << averageGrade << endl;

    return 0;
}

Output

Average Grade: 85.1667

Explanation

  • The calculateAverageGrade function takes an array of Student objects and the array size as arguments.
  • It calculates and returns the average grade of the students.
  • The main function initializes the array, calls the calculateAverageGrade function, and prints the average grade.

Example 2: Finding the Youngest Student

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;
    double grade;

    Student(string n, int a, double g) : name(n), age(a), grade(g) {}

    void display() {
        cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
    }
};

int findYoungestStudent(Student students[], int size) {
    int youngestIndex = 0;
    for (int i = 1; i < size; i++) {
        if (students[i].age < students[youngestIndex].age) {
            youngestIndex = i;
        }
    }
    return youngestIndex;
}

int main() {
    Student students[3] = {
        Student("Aarav", 20, 88.5),
        Student("Siya", 21, 92.0),
        Student("Rohan", 19, 75.0)
    };

    int size = 3;
    int youngestIndex = findYoungestStudent(students, size);

    cout << "Youngest Student: " << students[youngestIndex].name
         << ", Age: " << students[youngestIndex].age << endl;

    return 0;
}

Output

Youngest Student: Rohan, Age: 19

Explanation

  • The findYoungestStudent function takes an array of Student objects and the array size as arguments.
  • It finds and returns the index of the youngest student.
  • The main function initializes the array, calls the findYoungestStudent function, and prints the details of the youngest student.

Example 3: Sorting Students by Grade

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

class Student {
public:
    string name;
    int age;
    double grade;

    Student(string n, int a, double g) : name(n), age(a), grade(g) {}

    void display() {
        cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
    }
};

// Comparator function to sort students by grade
bool compareGrades(Student a, Student b) {
    return a.grade > b.grade; // Sort in descending order
}

int main() {
    Student students[3] = {
        Student("Aarav", 20, 88.5),
        Student("Siya", 21, 92.0),
        Student("Rohan", 19, 75.0)
    };

    int size = 3;

    // Sort the students by grade
    sort(students, students + size, compareGrades);

    // Print sorted student data
    for (int i = 0; i < size; i++) {
        students[i].display();
    }

    return 0;
}

Output

Name: Siya, Age: 21, Grade: 92
Name: Aarav, Age: 20, Grade: 88.5
Name: Rohan, Age: 19, Grade: 75

Explanation

  • The compareGrades function is a comparator function used to sort students by their grades in descending order.
  • The sort function from the <algorithm> header sorts the array of students using the compareGrades function.
  • The sorted array is printed, showing students ordered by their grades.

Conclusion

An array of objects in C++ provides a structured way to manage and manipulate collections of instances of a class. This chapter covered the basics of defining a class and creating an array of objects, along with practical examples demonstrating how to calculate the average grade, find the youngest student, and sort students by grade. Understanding how to use arrays of objects effectively is essential for organizing and processing complex data in C++ programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top