Mega Code Archive

 
Categories / C++ Tutorial / Development
 

Allocate memory for an object

#include <iostream>  #include <new>  using namespace std;    class Rectangle {    int width;    int height;  public:    Rectangle(int w, int h) {      width = w;      height = h;      cout << "Constructing " << width << " by " << height << " rectangle.\n";    }      ~Rectangle() {        cout << "Destructing " << width << " by " << height << " rectangle.\n";    }       int area() {      return width * height;    }  };    int main()  {    Rectangle *p;      try {      p = new Rectangle(10, 8);    } catch (bad_alloc xa) {      cout << "Allocation Failure\n";      return 1;    }      cout << "Area is " << p->area();      delete p;      return 0;  } Constructing 10 by 8 rectangle. Area is 80Destructing 10 by 8 rectangle.