Write your question here.
Hello, I am creating a class that has a private array on the heap with a constructor that takes the size of the array and initializes it on the heap. Later I have to make a deconstructor delete the space and print out free after.
In my code, I was able to heap a private array and make a deconstructor, but I don't know how to take the size of the array and initialize it on the heap.
My guess is this:
int* size = new int();
Also when you initialize size on the heap, don't you also have to delete it too? If so, where, in the code, do you do that?
Class Student
{
private:
int size;
int* array = newint[size];
public:
Student(); // Constructor
~Student(); // Deconstructor
}
Student::Student()
{
// How do you make a constructor that takes the size of the array and initializes it on the heap
}
Student::~Student()
{
delete[] array;
cout << "Free!" << endl;
}
First you can not do this : -
int* array = new int[size];
means you cant initialize here this array pointer.
simply define : - int* array;
As we know constructor is to initialize your object, So you can initialize here the value of size and array pointer;
So, finally your constructor become:-
Student::Student() //default constructor
{
size = 10; //initialize size with default value
array = new int[size]; //allocate memory for 10 elements in array on heap
}
Now,If you want to initialize size from user,You have to write parameterized constructor,
Student::Student(int arraySize) //parameterized constructor
{
size = arraySize; //initialize size with default value
array = new int[size]; //allocate memory for 'size' elements in array on heap
}
int main()
{
Student objS;
//default constructor call n allocate memory for array having 10 elements
Student objS1(7);
//parameterized constructor call n allocate memory for array 7 //elements