Recreating a basic Dynamic Array
Create a class DynamicArray that managers an int array. It should haveA
- A
int* array, andint sizemember. - A constructor that accepts the size of the array and initializes it with zeroes.
- A destructor that frees the allocated memory.
- A method to print the array.
Demonstrate the program by creating a DynamicArray object in a function call, and let the object go out of scope.
Answer
#include <iostream>
class DynamicArray {
public:
int* array;
int size;
// Constructor
DynamicArray(int _size) {
size = size;
array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = 0; // Initialize with zeroes
}
std::cout << "Array of size " << size << " created.\n";
}
// Destructor
~DynamicArray() {
delete[] array;
std::cout << "Array of size " << size << " deleted.\n";
}
// Method to print the array
void printArray() {
for (int i = 0; i < size; i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
}
};
// Function to demonstrate the DynamicArray class destructor
void demonstrateDynamicArray() {
DynamicArray da(5); // Create a DynamicArray object of size 5
da.printArray(); // Print the array
} // Destructor will be automatically called when function returns
int main() {
demonstrateDynamicArray();
return 0;
}