Dynamic initialization of objects in C++
Dynamic initialization of objects in C++ involves allocating memory for objects on the heap using the `new` operator. This is in contrast to the traditional stack-based allocation that occurs when objects are created using regular constructors. Dynamic initialization is particularly useful when you need to manage the lifetime of objects manually or when you want to create objects with a variable size or quantity.
Here's an example demonstrating dynamic initialization of objects:
#include <iostream>
#include <string>
class Student {
public:
// Parameterized constructor
Student(const std::string& n, int a) : name(n), age(a) {}
// Display information about the student
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
private:
std::string name;
int age;
};
int main() {
// Dynamic initialization of a single object
Student* student1 = new Student("Alice", 20);
// Display information about the dynamically initialized student
student1->displayInfo();
// Dynamic initialization of an array of objects
const int numStudents = 3;
Student* studentArray = new Student[numStudents] {
{"Bob", 22},
{"Charlie", 19},
{"David", 21}
};
// Display information about the dynamically initialized array of students
for (int i = 0; i < numStudents; ++i) {
studentArray[i].displayInfo();
}
// Remember to free the dynamically allocated memory
delete student1;
delete[] studentArray;
return 0;
}
In this example:
- The `new` operator is used to dynamically allocate memory for a single `Student` object (`student1`) and an array of `Student` objects (`studentArray`).
- The `delete` operator is used to free the memory allocated for the single object.
- The `delete[]` operator is used to free the memory allocated for the array of objects.
It's important to manage memory properly when using dynamic initialization to avoid memory leaks. For every `new` operation, there should be a corresponding `delete` or `delete[]` operation to release the allocated memory. Alternatively, modern C++ practices often recommend using smart pointers like `std::unique_ptr` or `std::shared_ptr` to automate memory management.
Comments
Post a Comment