Arrays Of Objects

When you define a class you create a new type. Arrays of that type can be created. In case the objects in the array need to be initialized, a short form initialization, similar to the one used for basic types is available. An array of integers can be initialized as:
int arr[3] = {1, 10, 100};
The same can be done for objects. Given a class ClassB, which has a constructor taking an integer as an argument, you can declare an array containing two objects of class ClassB and initialize them in the following manner:
ClassB array2[2] = {ClassB(5), ClassB(13)}; 
In the example below, three classes are defined. ClassA has only the default constructor, taking no parameters. ClassB has a one parameter constructors, ClassC has a two parameter constructor. The array of ClassA elements can receive no parameter list when declared. The array of ClassB elements may receive a parameter list when declared, in this case you have to provide the constructors for all elements. The same holds for the array of ClassC elements. NB: arrays of objects with one-parameter constructors are a special case: the list of parameters can be provided without the constructor function.


Example


#include <iostream>
using namespace std;

class ClassA
{
};

class ClassB
{
     int b;
public:
     ClassB(int x)
     {
        b = x;
     }
};

class ClassC
{
     int c;
     char d;
public:
     ClassC(int y, char z)
     {
        c = y;
        d = z;
     }
};

int main()
{
     ClassA array1[3];    // creates an array of three ClassA objects
     ClassB array2[2] = {ClassB(5), ClassB(13)};  // array of two
                           //elements, single parameter constructor
     ClassC array4[2] = {ClassC(2, 'f'), ClassC(34, 'l')}; // double-parameter constructor
     ClassB array3[2] = {71, 5};  // constructors taking one parameter
                                  // are a special case
}