Dynamic memory allocation in C++
allows for the creation of objects at
runtime, providing flexibility when the
size or number of objects isn’t known at
compile time. This is achieved using the
new and delete operators.
Here’s an example demonstrating
dynamic allocation of a Student object:
#include <iostream>
#include <cstring>
class Student {
private:
char* name;
public:
// Constructor
Student(const char* studentName) {
name = new char[strlen(studentName) + 1]; //
Allocate memory
strcpy(name, studentName);
}
// Destructor to free memory
~Student() {
delete[] name;
std::cout << "Memory freed for student." <<
std::endl;
}
// Member function to display the name
void display() const {
std::cout << "Student Name: " << name <<
std::endl;
}
};
int main() {
// Dynamically allocate a Student object
Student* s = new Student("Alice");
// Use the object
s->display();
// Deallocate memory
delete s; // Destructor gets called
return 0;
}
Explanation:
• Dynamic Allocation: The new
operator allocates memory on the
heap for a Student object and calls its
constructor with the provided name.
• Accessing Members: The arrow
operator (->) is used to access the
display member function through the
pointer s.
• Deallocation: The delete operator
frees the allocated memory and calls
the destructor of the Student object.
Using dynamic allocation is beneficial
when the lifetime of an object needs to
extend beyond the scope in which it
was created or when managing
resources that require precise control
over their allocation and deallocation.
It’s crucial to ensure that every new
operation has a corresponding delete
to prevent memory leaks. This practice
aligns with the Resource Acquisition Is
Initialization (RAII) principle, which ties
resource management to object
lifetime.
For more advanced memory
management, C++11 introduced
smart pointers like std::unique_ptr and
std::shared_ptr, which automatically
manage the lifetime of dynamically
allocated objects.
If you have further questions or need
additional examples, feel free to ask!