title: Writing a destructor for a class containing a dynamically allocated array member c++
body: <p>(C++ code)
  Suppose I have a class like:</p>
  
  <pre><code>class A {
  public: 
     int * ptr;
     int size;
      A();
      ~A();
  }
  
  A::A()
  {
      ptr = new int[10];  // memory allocation is dependent upon user input into size variable 
  }
  A::~A()
  { 
      delete [] ptr; 
  }
  </code></pre>
  
  <p>According to what I could find (sample link: <a href="https://stackoverflow.com/questions/9498384/how-delete-a-pointer-of-classes-which-has-pointer-members">How delete a pointer of classes which has pointer members?</a>) this seems to be the correct way of defining the destructor here. But I tried this and it runs into run time exception. 
  Even tried, <code>delete ptr;</code> but no luck </p>
  
  <p>Is this the correct way of doing things?    </p>
  
  <p>The array based implementation of queue : </p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;string&gt;
  using namespace std;
  
  class ArrayQueue
  {
  public:
      int front, size, rear, curr;
      int * elem;
      ArrayQueue():size(10),rear(-1),curr(0),front(-1){}
      ArrayQueue(int n);
      void enqueue(int&amp; e);
      void dequeue();
      bool empty()const;
      int&amp; getFront() const;
      int&amp; getRear() const;
      int&amp; getSize();
      ~ArrayQueue();
  
  };
  
  ArrayQueue::ArrayQueue(int n)
  {
      size = n;
      front = -1;
      rear=-1;
      curr=0;
      elem = new int[size];
  }
  ArrayQueue::~ArrayQueue()
  {  cout&lt;&lt;"running destructor";
      delete[] elem;
  }
  
  bool ArrayQueue::empty()const
  {
      return  curr==0;
  }
  int&amp; ArrayQueue::getSize()
  {
      return curr;
  }
  int&amp; ArrayQueue::getFront()const
  {
      return elem[front];
  }
  int&amp; ArrayQueue::getRear()const
  {
      return elem[rear];
  }
  void ArrayQueue::enqueue(int&amp; e)
  {
      if(getSize()==size){cout&lt;&lt;"Queue full"&lt;&lt;'\n'; return;}
      rear = ((rear+1)%size);
      elem[rear]=e;
      ++curr;
  }
  void ArrayQueue::dequeue()
  {
      if(empty()){cout&lt;&lt;"Queue empty"&lt;&lt;'\n';return;}
      front = ((front+1)%size);
      --curr;
  }
  
  
  int main()
  {
      ArrayQueue object;
      cout&lt;&lt;"Size of the queue"&lt;&lt;object.size&lt;&lt;'\n';
      cout&lt;&lt;"Current size:"&lt;&lt;object.getSize()&lt;&lt;'\n';
      object.dequeue();
      for(int i =0 ; i&lt;15; i++)
      {
          object.enqueue(i);
      }
      cout&lt;&lt;"front element : "&lt;&lt;object.front&lt;&lt;'\n';
      cout&lt;&lt;"rear element : "&lt;&lt;object.rear&lt;&lt;'\n';
      cout&lt;&lt;"Current size:"&lt;&lt;object.getSize()&lt;&lt;'\n';
      object.dequeue();
      object.dequeue();
      object.dequeue();
      cout&lt;&lt;"front element : "&lt;&lt;object.front&lt;&lt;'\n';
      cout&lt;&lt;"rear element : "&lt;&lt;object.rear&lt;&lt;'\n';
      return 0;
  }
  </code></pre>