|

In
C++ an array name is a constant pointer to the first
element of the array. Therefore, in the declaration
CAT
Family[50];
Family
is a pointer to &Family[0], which is the address
of the first element of the array Family.
It
is legal to use array names as constant pointers,
and vice versa. Therefore, Family + 4 is a legitimate
way of accessing the data at Family[4].
The
compiler does all the arithmetic when you add to,
increment, and decrement pointers. The address accessed
when you write Family + 4 isn’t 4 bytes past the
address of Family—it is four objects. If each object
is 4 bytes long, Family + 4 is 16 bytes. If each
object is a CAT that has four long member variables
of 4 bytes each and two short member variables of
2 bytes each, each CAT is 20 bytes, and Family +
4 is 80 bytes past the start of the array.
Listing
11.7 illustrates declaring and using an array on
the free store.
Listing
11.7. Creating an array by using new.
1:
// Listing 11.7 - An array on the free store
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:
CAT :: ~CAT()
20:
{
21:
// cout << "Destructor called!\n";
22:
}
23:
24:
int main()
25:
{
26:
CAT * Family = new CAT[500];
27:
int i;
28:
CAT * pCat;
29:
for (i = 0; i < 500; i++)
30:
{
31:
pCat = new CAT;
32:
pCat->SetAge(2*i +1);
33:
Family[i] = *pCat;
34:
delete pCat;
35:
}
36:
37:
for (i = 0; i < 500; i++)
38:
{
38:
cout << "Cat #" << i+1 << ": ";
39:
cout << Family[i].GetAge() << endl;
40:
}
41:
42:
delete [] Family;
43:
44:
return 0;
45:
}
OUTPUT:
Cat #1: 1
Cat #2: 3
Cat #3: 5
...
Cat #499: 997
Cat #500: 999
ANALYSIS: Line 26 declares the array
Family, which holds 500 CAT objects. The entire
array is created on the free store with the call
to new CAT[500].
Each
CAT object added to the array also is created on
the free store (line 31). Note, however, that the
pointer isn’t added to the array this time; the
object itself is. This array isn’t an array of pointers
to CATs. It is an array of CATs.
|