Initialize an array of objects by referencing the constructor directly : object array « Class « C++ Tutorial





#include <iostream> 
using namespace std; 
 
class MyClass { 
  int x; 
public: 
  MyClass(int i) { x = i; } 
  int getX() { return x; } 
}; 
 
int main() 
{ 
  MyClass obs[4] = { MyClass(-1), MyClass (-2), 
                   MyClass (-3), MyClass (-4) };
  int i; 
 
  for(i=0; i < 4; i++) 
    cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n"; 
 
  return 0; 
}
obs[0].getX(): -1
obs[1].getX(): -2
obs[2].getX(): -3
obs[3].getX(): -4










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.