Arrays of objects in C++ allow you to create a collection of objects of the same class within a single array. This is useful when you need to manage a group of similar objects together.
Here’s a breakdown of the concept:
class MyClass {
private:
MyClass objects[size]; // Array of MyClass objects
// ... other members
public:
// ... member functions
};
Example:
class Book {
public:
std::string title;
std::string author;
Book(const std::string& title, const std::string& author) : title(title), author(author) {}
};
int main() {
Book myBooks[3]; // Array of 3 Book objects
myBooks[0] = Book("The Lord of the Rings", "J.R.R. Tolkien");
myBooks[1] = Book("Pride and Prejudice", "Jane Austen");
myBooks[2] = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams");
for (int i = 0; i < 3; ++i) {
std::cout << "Book " << i + 1 << ": " << myBooks[i].title << " by " << myBooks[i].author << std::endl;
}
return 0;
}
vector<MyClass>
for more features like automatic resizing and potentially better memory management.