Pointers and Array Names

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 past it. 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 15.5 illustrates declaring and using an array on the heap.

Listing 15.5. Creating an Array by Using new
 0:  // Listing 15.5 - An array on the heap
 1:  #include <iostream>
 2:
 3:  class CAT
 4:  {
 5:  public:
 6:      CAT() { itsAge = 1; itsWeight=5; }       // default constructor
 7:      ~CAT();                                  // destructor
 8:      int GetAge() const { return itsAge; }
 9:      int GetWeight() const { return itsWeight; }
10:      void SetAge(int age) { itsAge = age; }
11:
12:  private:
13:      int itsAge;
14:      int itsWeight;
15:  };
16:
17:  CAT :: ~CAT()
18:  {
19:  //  std::cout << "Destructor called!
";
20:  }
21:
22:  int main()
23:  {
24:      CAT * Family = new CAT[500];
25:      int i;
26:      CAT * pCat;
27:      for (i = 0; i < 500; i++)
28:      {
29:          pCat = new CAT;
30:          pCat->SetAge(2*i +1);
31:          Family[i] = *pCat;
32:          delete pCat;
33:      }
34:
35:      for (i = 0; i < 500; i++)
36:          std::cout << "Cat #" << i+1 << ": "
37:              << Family[i].GetAge() << std::endl;
38:
39:      delete [] Family;
40:
41:      return 0;
42:  }


Cat #1: 1
Cat #2: 3
Cat #3: 5
...
Cat #499: 997
Cat #500: 999

Line 24 declares the array Family, which holds 500 CAT objects. The entire array is created on the heap with the call to new CAT[500].


Technically, line 24 declares an unnamed array on the heap and returns the address of its first element to the pointer Family. It is customary to refer to that pointer as the array itself. In fact, whenever you declare an array (even on the stack) the array name is really just a pointer to the first element.


Each CAT object added to the array also is created on the heap (line 29). 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.138.178