In: Computer Science
C++ Memory Management:
- Create a class called DynamicArray that allocates an integer array of user defined size on the heap
- Don't not use any of the STL containers (vector, list, etc)
- Create the necessary constructors and destructor, code should allocate the array using new.
- Write a method print_array that prints the array’s length and the contents of the array.
- Create at least 2 DynamicArray objects and print their contents. Include your DynamicArray class below along with the constructors/destructor and sample output.
- Below is a sample main method that declares, fills (not required as part of the project, but it makes testing easier), and prints a DynamicArray
int main()
{
DynamicArray a(9);
a.fill_array(1); /* fills array with consecutive #’s */
a.print_array();
}
- in the comments label code as 'constructor' and 'destructor'
-show full code to pls
#include <iostream>
using namespace std;
class DynamicArray {
// Access specifier
public:
//Data Members
int *data;
int n, size;
//Member Functions()
//Default constructor
DynamicArray() {
data = new int[8];
n = 8;
size = 0;
}
DynamicArray(int size) {
data = new int[size];
n = size;
size = 0;
}
//Copy constructor
DynamicArray(const DynamicArray &other) {
n = other.n;
data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = other.data[i];
}
}
void operator=(const DynamicArray &other){
n = other.n;
data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = other.data[i];
}
}
int countEntry(){
return size;
}
void fill_array(int k){
while(1) {
data[size++] = k;
if(size==n)
break;
}
}
void print_array(){
for (int i = 0; i < size; i++) {
cout<< data[i] <<" ";
}
cout<<endl;
}
//Destructor
~DynamicArray() {
delete[] data;
}
};
int main(){
DynamicArray a(9);
a.fill_array(1);
a.print_array();
}
=================================================================
SEE OUTPUT
Thanks, PLEASE COMMENT if there is any concern. PLEASE UPVOTE