< previous page page_229 next page >

Page 229
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write
int IntegerArray[] = { 10, 20, 30, 40, 50 };
you will create exactly the same array as you did in the previous example.
If you need to know the size of the array, you can ask the compiler to compute it for you. For example,
const int IntegerArrayLength = sizeof(IntegerArray)/sizeof(IntegerArray[0]);
sets the constant int variable IntegerArrayLength to the result obtained from dividing the size of the entire array by the size of each individual entry in the array. That quotient is the number of members in the array.
You cannot initialize more elements than you've declared for the array. Therefore,
int IntegerArray[5] = { 10, 20, 30, 40, 50, 60};
generates a compiler error because you've declared a five-member array and initialized six values. It is legal, however, to write
int IntegerArray[5] = { 10, 20};
Although uninitialized array members have no guaranteed values, actually, aggregates will be initialized to 0. If you don't initialize an array member, its value will be set to 0.
Arrays of Objects
Any object, whether built-in or user defined, can be stored in an array. When you declare the array, you tell the compiler the type of object to store and the number of objects for which to allocate room. The compiler knows how much room is needed for each object based on the class declaration. The class must have a default constructor that takes no arguments so that the objects can be created when the array is defined.
Accessing member data in an array of objects is a two-step process. You identify the member of the array by using the index operator ([ ]), and then you add the member operator (.) to access the particular member variable. Listing 15.2 demonstrates how you would create an array of five CATs.

 
< previous page page_229 next page >

If you like this book, buy it!