If the size of the array is known at compile time, I tend to use std::array
class Student {
public:
Student() {
std::cout << "Student Created\n";
}
~Student() {
std::cout << "Student Deleted\n";
}
int a;
};
int main() {
std::array<Student*, 5> arr;
arr[1] = new Student();
arr[1]->a = 42;
std::cout << arr[1]->a << std::endl;
delete arr[1]; // Don't forget to call the destructor
return 0;
}
Output:
Student Created
42
Student Deleted
Note, that arr won't initialize elements to nullptr, might contain memory garbage. Also, don't forget to clean up when you're done.
Better approach would be to use RAII as follows:
class Student {
public:
Student() {
std::cout << "Student Created\n";
}
~Student() {
std::cout << "Student Deleted\n";
}
int a;
};
int main() {
std::array<std::unique_ptr<Student>, 5> arr;
arr[1] = std::make_unique<Student>();
arr[1]->a = 42;
std::cout << arr[1]->a << std::endl;
// No delete needed here, unique_ptr will take care of lifetime management
return 0;
}
Same output, but safer:
Student Created
42
Student Deleted