top of page
Writer's picturecompnomics

Arrays of Objects in C++



Arrays of objects are a powerful way to store and manage multiple objects of the same class in C++. They allow you to efficiently store and access collections of related data.


Creating Arrays of Objects

To create an array of objects, you simply declare an array of the class type. The size of the array specifies the number of objects you want to store.

#include <iostream>

using namespace std;

class Person {
public:
    string name;
    int age;

    Person(string name, int age) {
        this->name = name;
        this->age = age;
    }
};

int main() {
    Person people[3];

    return 0;
}

Accessing and Modifying Array Elements

You can access and modify individual elements of the array using the index operator ([]).

people[0].name = "Alice";
people[0].age = 25;

cout << people[0].name << endl;
cout << people[0].age << endl;

Iterating Over Arrays

You can iterate over an array of objects using a for loop.

for (int i = 0; i < 3; i++) {
    cout << people[i].name << " is " << people[i].age << " years old." << endl;
}

Example: Student Management

#include <iostream>

using namespace std;

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

    Student(string name, int rollNumber, double grade) {
        this->name = name;
        this->rollNumber = rollNumber;
        this->grade = grade;
    }
};

int main() {
    Student students[5];

    // Populate the array with student data
    students[0] = Student("Alice", 1, 95.0);
    students[1] = Student("Bob", 2, 88.5);
    // ...

    // Iterate over the array and print student information
    for (int i = 0; i < 5; i++) {
        cout << "Student " << students[i].rollNumber << ": " << students[i].name << endl;
        cout << "Grade: " << students[i].grade << endl;
    }

    return 0;
}

Key points:

  • Arrays of objects can be used to store collections of related data.

  • You can access and modify individual elements of an array using the index operator.

  • You can iterate over arrays using a for loop.

  • Arrays of objects can be used to implement various data structures and algorithms.


By understanding how to create and manipulate arrays of objects, you can write more efficient and organized C++ code.

31 views0 comments

Recent Posts

See All

Kommentare

Mit 0 von 5 Sternen bewertet.
Noch keine Ratings

Rating hinzufügen
bottom of page