< previous page page_230 next page >

Page 230
LISTING 15.2 CREATING AN ARRAY OF OBJECTS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:    // Listing 15.2 - An array of objects
 2:
 3:    #include <iostream.h>
 4:
 5:    class CAT
 6:    {
 7:    public:
 8:       CAT() { itsAge = 1; itsWeight=5; }  // default constructor
 9:       ~CAT() {}                                   // destructor
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:          cout << Cat # << i+1<< :  << Litter[i].GetAge() << endl;
28:       return 0;
29:    }

Output:
cat #1: 1
cat #2: 3
cat #3: 5
cat #4: 7
cat #5: 
Analysis: Lines 517 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.

 
< previous page page_230 next page >

If you like this book, buy it!