We’ve talked about arrays and objects before, but now we’re going to look at an array of objects.
Consider a situation where you had a class called Student. While you would often need to work with a singular student, you could very likely also need to have multiple students, for example, if you were talking about everyone in a major, or even a classroom. So being able to create an array of objects is important.
Creating the Array of Objects
Consider the simple example below. What do you think is happening here?
Circle circles[10];
Here you see an object we’ve worked with before, Circle. We’re creating an array of ten of these circles. However, since we’ve not defined their radius in calling the constructor, each of these will have the same radius, because they were created with the no-arg constructor.
If you want to create an array, and pass in a value(s) to the constructor, you need to do something like:
Circle circles[] = {Circle(1), Circle(3), Circle(5)};
Notice how we use the braces {}, just like we have previously with an array, but we’re calling the constructor with a value of our choosing.
Using the Array of Objects
At this point, it is just like using an array, and using an object.
We specify which element of our array by using the index, and can call on existing methods. We can pass the array to a function, or specify an element.
// print the value returned by the method of the second element of circles
cout << circles[1].getArea() << endl;
// pass all elements to a function
getTotalArea(circles, sizeOfCircles);
// pass a single element to a function
performMagic(circles[0]);
Arrays of C++ Objects was originally found on Access 2 Learn