Destructor for Dynamic Array in C++
Dynamic memory allocation in C++ allows us to allocate memory during program execution using the pointers. This memory is wholly managed by the programmer from allocation to deallocation. So, when we declare a dynamic member in a class, it is our responsibility to deallocate the memory for that class when the object is destroyed. In this article, we will learn how to implement destructors for dynamic arrays in C++.
Deleting Dynamic Array using Class Destructor in C++
When working with dynamic arrays in C++, it’s essential to create a destructor for classes that deallocates the memory allocated to the dynamic arrays.
In this destructor, we can use the delete [] operator to allocate memory for dynamic arrays.
Syntax
delete[] dynamic_Array;
The allocated heap memory is not deallocated automatically by the compiler and it must be explicitly deallocated by the user through destructors. The delete[] operator deallocates the entire memory that was allocated for the dynamic array into the heap.
C++ Program to Deleting Dynamic Array using Class Destructor
The following program illustrates how we can implement a destructor for dynamic arrays in C++:
// C++ Program to Implement Destructor for Dynamic Arrays
#include <iostream>
using namespace std;
// dynamic array class
class DynamicArray {
private:
// pointer to the heap memory
int* arr;
int size;
public:
DynamicArray(int s)
{
size = s;
// allocating memory
arr = new int[size];
}
// Destructor to deallocate memory for the dynamic array
~DynamicArray()
{
cout << "Memory for the Dynamic Array Released"
<< endl;
delete[] arr;
}
// Function to add elements to the array
void addElement(int index, int value)
{
if (index >= 0 && index < size) {
arr[index] = value;
}
}
// Function to print the elements of the array
void printArray()
{
cout << "Array elements:" << endl;
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
// some other functions can go here when needed
};
int main()
{
// Create a dynamic array object
DynamicArray dynArray(10);
// Add some elements to the dynamic array
for (int i = 0; i < 10; ++i) {
dynArray.addElement(i, i * 2);
}
// Print the elements of the dynamic array
dynArray.printArray();
// The destructor will be called automatically when the
// object goes out of scope and the memory will be freed
return 0;
}
Output
Array elements: 0 2 4 6 8 10 12 14 16 18 Memory for the Dynamic Array Released
Time Complexity: O(1) as deallocation does not depend on the size of the memory.
Auxiliary Space: O(1)
Contact Us