Arrays of objects C++ Programming

You can create arrays of objects in C++ and many other programming languages just like you would create arrays of any other data type. When you need to store and manage numerous instances of a class or objects of a specific type, you use object arrays. The following describes how to use object arrays in C++:

  • Define a Class: First, create a class that represents the type of objects you want to store in the array. 

      For example:

class Persons {
public:
    string name;
    int age;

    Persons(string n, int a) : name(n), age(a) {}                           // Constructor
};

Explanation of this program:-We defined a 'Person' class with attributes 'name' and 'age'.

  • Create an Array of Objects: You can then make an array of objects of that class. To make an array of 'Person' objects, for example:
Persons people[5];       // Creates an array of 5 Person objects
Persons* people = new Persons[5];   // Creates an array of 5 Person objects on the heap
  • Initialize Objects in the Array: You can simply initialize the array's objects or use a loop:
people[0] = Persons("Alice", 20);
people[1] = Persons("Bob", 25);
// ... and so on

Or, with a loop:

for (int j = 0; j < 5; j++) {
    string name;
    int age;
    cout << "Enter name for person " << j + 1 << ": ";
    cin >> name;
    cout << "Enter age for person " << j + 1 << ": ";
    cin >> age;
    people[j] = Persons(name, age);
}
  • Access and Manipulate Objects: The array index notation can be used to access and manipulate the objects in the array. For example:
cout << "Name of the first person: " << people[0].name << endl;
cout << "Age of the second person: " << people[1].age << endl;
  • Clean Up (if necessary): If you used dynamic memory allocation to create the array, remember to free the memory when you're done:
delete[] people;