|

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 11.4 demonstrates how you
would create an array of five CATs.
Listing
11.4. Creating an array of objects.
1:
// Listing 11.4 - An array of objects
2:
3:
#include <iostream.h>
4:
5:
class CAT
6:
{
7:
public:
8:
CAT() { itsAge = 1; itsWeight=5; }
9:
~CAT() {}
10:
int GetAge() const { return itsAge; }
11:
int GetWeight() const { return itsWeight; }
12:
void SetAge(int age) { itsAge = age; }
13:
14:
private:
15:
int itsAge;
16:
int itsWeight;
17:
};
18:
19:
int main()
20:
{
21:
CAT Litter[5];
22:
int i;
23:
for (i = 0; i < 5; i++)
24:
Litter[i].SetAge(2*i +1);
25:
26:
for (i = 0; i < 5; i++)
27:
{
28:
cout << "Cat #" << i+1<< ": ";
29:
cout << Litter[i].GetAge() << endl;
30:
}
31:
return 0;
32:
}
OUTPUT:
cat #1: 1
cat #2: 3
cat #3: 5
cat #4: 7
cat #5: 9
ANALYSIS: Lines 5-17 declare the CAT
class. The CAT class must have a default constructor
so that CAT objects can be created in an array.
Remember that if you create any other constructor,
the compiler-supplied default constructor is not
created; you must create your own.
The first for loop (lines 23 and 24) sets the age
of each of the five CATs in the array. The second
for loop (lines 26 and 27) accesses each member
of the array and calls GetAge().
Each
individual CAT’s GetAge() method is called by accessing
the member in the array, Litter[i], followed by
the dot operator (.), and the member function.
|