Arrays of Class Objects

You can declare arrays of objects in the same way that you can declare arrays of any other data type. For example:

Date birthdays[10];

When you declare an array of objects, the constructor is called for each element in the array. If you want to be able to declare arrays without initializing them, the class must have a default constructor (that is, one that can be called without arguments). In the above example, the default Date constructor is called, initializing each element in the array to January 1, 1.

You can also provide initializers for each element in the array by explicitly calling the constructor with arguments. If you don't provide enough initializers for the entire array, the default constructor is called for the remaining elements. For example:

Date birthdays[10] = { Date( 2, 10, 1950 ),

Date( 9, 16, 1960 ),

Date( 7, 31, 1953 ),

Date( 1, 3, 1970 ),

Date( 12, 2, 1963 ) };

The above example calls the Date constructor that takes three parameters for the first five elements of the array, and the default constructor for the remaining five elements.

Notice the syntax for calling a constructor explicitly. Unlike the usual syntax which declares an object and initializes it, this syntax creates an object with a particular value directly. This is analogous to specifying the integer constant 123 instead of declaring an integer variable and initializing it.

If the class has a constructor that takes only one argument, you can specify just the argument as the initializer for an element. You can also mix different styles of initializer. For example:

String message[10] = { "First line of message\n",

"Second line of message\n",

String( "Third line of message\n"),

String( '-', 25 ),

String() };

In the above example, the single-parameter constructor is called for the first three elements of the array, implicitly for the first two elements, and explicitly for the third. The two-parameter constructor is called explicitly for the fourth element. The default constructor is called explicitly for the fifth element, and implicitly for the remaining five elements.