• Home
  • Array of Objects in C++ with Examples

Array of Objects in C++ with Examples

An array of objects in C++ is an array that holds objects of a certain class type. It can be declared in the following way:

ClassName object_name[array_size];

For example, if you have a class called Person and you want to create an array of 5 Person objects, you can do it like this:

Person persons[5];
You can also initialize the array with objects of the Person class like this:

Copy code

Person persons[5] = {Person("John", 25), Person("Alice", 30), Person("Bob", 35), Person("Kate", 40), Person("Mia", 45)};

You can access and modify the elements of the array using the array index. For example, to access the first element of the persons array, you can do it like this:

cout << persons[0].getName() << endl;

You can also use a loop to iterate through the elements of the array. For example:

for (int i = 0; i < 5; i++) {
cout << persons[i].getName() << endl;
}

You can also use the vector container in C++ to store a dynamic array of objects.

I hope this helps! Let me know if you have any questions.