Using new and delete of array : delete « Development « C++ Tutorial






#include <iostream.h>

class Point
{
    int x;
    int y;
public:
   Point(){ 
      x = 0; 
      y = 0;
   }
   
   Point(int a,int b=0)  { 
      x = a; 
      y= b; 
   }
   void Set (int a,int b=0) { 
      x = a; 
      y = b; 
   }
   void Display() {
        cout << "x = "<< x << " y = "<< y   << endl;
   }
   ~Point() {
        cout << "Destruct obj.\n" ;
   }
};

int main()
{
    Point *p;int i;
    const int Length = 3;
    p=new Point[Length];
    
    if(!p)
    {  
        cout << "allocation failure\n";  
        return -1;  
    }
    for (i=0;i<Length;i++)
        p[i].Set(i*10,-i*10);
    for (i=0;i<Length;i++)
        p[i].Display();
    delete []p;
    return 0;
}
x = 0 y = 0
x = 10 y = -10
x = 20 y = -20
Destruct obj.
Destruct obj.
Destruct obj.








5.13.delete
5.13.1.Memory management new-delete
5.13.2.Delete an array of objects
5.13.3.Global delete
5.13.4.object in existence after deletion
5.13.5.delete class array and return memory to heap
5.13.6.Using new and delete of array