I am having trouble understanding how to write the destructor in the second class of the program below:
class First
{
// Assume this is a virtual class
};
class Second
{
private:
int index;
First **arr;
public:
Second(int size)
{
index = 0;
arr = new First*[size]; // Please bear with my use of new
}
~Second() {}
void add(First *f)
{
arr[index++] = f;
}
};
In all of the similar questions I found, each element of the array is assigned a value dynamically, using new as such: arr[i] = new First(); . However, here the elements are assigned the value of a pointer to an object that is a parameter of the function. So, should the destructor delete every element one by one and then delete the array, or is ti enough to delete the array?
~Second()
{
for(int i = 0; i < index; ++i) delete[] arr[i]; // Is this necessary?
delete[] arr;
}
arrwasnew[]-ed, so it should bedetele[]-ed. Wasarr[i]new[]-ed?First **arrwithstd::vector<First*>or, ifSecondowns theFirsts, withstd::vector<std::unique_ptr<First>>.fwere created,new,new[],malloc, or&variable? And also on whether the code callingaddwill retain ownership and delete the objects later. "Painting yourself into a corner" is a phrase that comes to mind.delete,delete[],free, or nothing. But if you don't know what the caller does, you cannot write it. :-)arrowns the array of pointers. What owns objects pointed to by array elements?