Sams Teach Yourself C++ in 21 Days

(singke) #1

Using Arrays of Objects ......................................................................................


Any object, whether built-in or user defined, can be stored in an array. When you declare
the array to hold objects, you tell the compiler the type of object to store and the number
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 13.4 demonstrates how you
would create and access an array of five Cats.

LISTING13.4 Creating an Array of Objects
0: // Listing 13.4 - An array of objects
1:
2: #include <iostream>
3: using namespace std;
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:

416 Day 13


Example 1
// assign ninth member of MyIntegerArray to theNinethInteger
int theNinethInteger = MyIntegerArray[8];
Example 2
// assign ninth member of ArrayOfPointersToLongs to pLong.
long * pLong = ArrayOfPointersToLongs[8];
Arrays count from zero. An array of nitems is numbered from 0 to nā€“1.
Free download pdf