OOP: ADVANCED OOP TOPICS
Arrays of Objects
An array of objects stores multiple objects of the same class type.
Example idea:
Student students[3];
This creates three Student objects.
Important Constructor Rule
If you create a fixed-size array like this:
Student students[3];
the class must have a default constructor, because each object is created without arguments.
Complete Example
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int marks;
public:
Student() : name("Unknown"), marks(0) {}
Student(string studentName, int studentMarks)
: name(studentName), marks(studentMarks) {}
void display() const {
cout << name << ": " << marks << endl;
}
};
int main() {
Student students[3] = {
Student("Riaz", 85),
Student("Nadia", 90),
Student("Karim", 78)
};
for (const Student& student : students) {
student.display();
}
return 0;
}
Output:
Riaz: 85
Nadia: 90
Karim: 78
Modern Alternative: vector
In modern C++, std::vector is often preferred because it can grow dynamically.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Book {
private:
string title;
public:
explicit Book(string bookTitle) : title(bookTitle) {}
void display() const {
cout << title << endl;
}
};
int main() {
vector<Book> books;
books.emplace_back("OOP in C++");
books.emplace_back("Data Structures");
for (const Book& book : books) {
book.display();
}
return 0;
}
Viva Answer
An array of objects stores multiple objects of the same class. If a fixed-size object array is created without initializer values, the class needs a default constructor. In modern C++, std::vector is often preferred for dynamic size.
Quick Check
- Why does
Student students[3];need a default constructor? - What is the advantage of
vectorover a fixed array? - How can we loop through an array of objects safely?