Understanding Pointers 241
19: using namespace std;^8
20: SimpleCat * Frisky = new SimpleCat;
21: cout << “Frisky is “ << Frisky->GetAge() << “ years old “ << endl;
22: Frisky->SetAge(5);
23: cout << “Frisky is “ << Frisky->GetAge() << “ years old “ << endl;
24: delete Frisky;
25: return 0;
26: }
Frisky is 2 years old
Frisky is 5 years old
On line 20, a SimpleCatobject that is pointed to by the pointer Friskyis instan-
tiated (created) on the free store. The default constructor of the object sets its age
to 2 , and the GetAge()method is called on line 21. Because Friskyis a pointer, the indi-
rection operator (->) is used to access the member data and functions. On line 22, the
SetAge()method is called, and GetAge()is accessed again on line 23.
Creating Member Data on the Free Store............................................................
In addition to creating objects on the free store, you can also create data members within
an object on the free store. One or more of the data members of a class can be a pointer
to an object on the free store. Using what you have already learned, you can allocate
memory on the free store for these pointers to use. The memory can be allocated in the
class constructor or in one of the class’ methods. When you are done using the member,
you can—and should—delete it in one of the methods or in the destructor, as Listing 8.7
illustrates.
LISTING8.7 Pointers as Member Data
1: // Listing 8.7 - Pointers as data members
2: // accessed with -> operator
3:
4: #include <iostream>
5:
6: class SimpleCat
7: {
8: public:
9: SimpleCat();
10: ~SimpleCat();
11: int GetAge() const { return *itsAge; }
12: void SetAge(int age) { *itsAge = age; }
13:
OUTPUT
LISTING8.6 continued
ANALYSIS