Allocate an array of objects using new operator : object array « Class « C++ Tutorial






#include <iostream> 
#include <new> 
using namespace std; 
 
class Rectangle { 
  int width; 
  int height; 
public: 
  Rectangle() {  
    width = height = 0; 
    cout << "Constructing " << width << " by " << height << " rectangle.\n"; 
  } 
 
  Rectangle(int w, int h) { 
    width = w; 
    height = h; 
    cout << "Constructing " << width << " by " << height << " rectangle.\n"; 
  } 
 
  ~Rectangle() {  
     cout << "Destructing " << width << " by " << height << " rectangle.\n"; 
  }  
 
  void set(int w, int h) { 
    width = w; 
    height = h; 
  } 
 
  int area() { 
    return width * height; 
  } 
}; 
 
int main() 
{ 
  Rectangle *p; 
 
  try { 
    p = new Rectangle [3]; 
  } catch (bad_alloc xa) { 
    cout << "Allocation Failure\n"; 
    return 1; 
  } 
 
  cout << "\n"; 
 
  p[0].set(3, 4); 
  p[1].set(10, 8); 
  p[2].set(5, 6); 
 
  for(int i=0; i < 3; i++) 
    cout << "Area is " << p[i].area() << endl; 
 
  delete [] p; 
 
  return 0; 
}
Constructing 0 by 0 rectangle.
Constructing 0 by 0 rectangle.
Constructing 0 by 0 rectangle.

Area is 12
Area is 80
Area is 30
Destructing 5 by 6 rectangle.
Destructing 10 by 8 rectangle.
Destructing 3 by 4 rectangle.








9.33.object array
9.33.1.Create an array of objects
9.33.2.An array of objects: call its method
9.33.3.Initialize an array of objects without referencing the constructor directly
9.33.4.Initialize an array of objects by referencing the constructor directly
9.33.5.Object array of derived classes
9.33.6.Allocate an array of objects using new operator
9.33.7.An array of pointers to objects
9.33.8.An array on the heap
9.33.9.Delete an array of objects
9.33.10.allocates and frees an object and an array of objects of type loc.