-1
#include <iostream>
using namespace std;
 
class Array
{
private:
    int *A;
    int size;
    int length;
public:
    Array (int size);
    void create();
    void display();
    ~Array();
};
Array::Array(int sz)
{
    sz = size;
    A = new int [sz];
}
void Array::create()
{
    cout<<"Enter number of elements: ";
    cin>>length;
    cout<<"Enter array elements"<<endl;
    for(int i{0}; i<length; i++)
    {
        cout<<" enter element at "<<i<<":"<<endl;
        cin>>A[i];
    }
}
void Array::display()
{
    for(int i{0}; i<length; i++)
        cout<<A[i]<<" ";
    cout<<endl;
}
Array::~Array()
{
    delete []A;
}
int main()
{
    int sz;
    cout<<"Enter size of array : ";
    cin>>sz;
    Array arr(sz);
    arr.create();
    arr.display();
    return 0;
}

i created this class as i was learning array adt, and practicing it. my question is do i have to call the destructor to free the dynamically allocated memory for the array. if yes how to call it in main. this class is made for practicing adt and of beginner level, i was stuck at the point coz we have to delete the memory allocated in heap to prevent the memory leakage, in static storage the destructor is called on its own after the scope finishes of the object.

  • https://stackoverflow.com/questions/33335668/how-to-free-an-array-in-c-c – agent_bean Aug 23 '22 at 15:27
  • 1
    The vast majority of the time the destructor is called for you, even when you set the chain of events in motion with `delete`. – user4581301 Aug 23 '22 at 15:31
  • 1
    You almost never call destructor explicitly. In rear cases when you do you would/should know what you are doing. – Slava Aug 23 '22 at 15:32
  • Useful reading: [What is meant by Resource Acquisition is Initialization (RAII)?](https://stackoverflow.com/q/2321511/4581301) – user4581301 Aug 23 '22 at 15:32
  • More handy reading [Storage Duration](https://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration), but the section on automatic and dynamic variables in your textbook will probably be easier to understand. – user4581301 Aug 23 '22 at 15:36
  • 1
    Side note: `Array` does not observe [the Rule of Three](https://en.cppreference.com/w/cpp/language/rule_of_three) This will lead to problems if an `Array` is copied or assigned. – user4581301 Aug 23 '22 at 15:37

1 Answers1

3

The array destructor will be called automatically at the end of the block in which it was created. In your case, this is main(). No, you don't have to call the destructor manually.

Cannon
  • 51
  • 2