< previous page page_153 next page >

Page 153
LISTING 10.3 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
10:       ~SimpleCat();
11:       int GetAge() const { return *itsAge; }
12:       void SetAge(int age) { *itsAge = age; }
13:
14:       int GetWeight() const { return *itsWeight; }
15:       void setWeight (int weight) { *itsWeight = weight; }
16:
17:   private:
18:       int * itsAge;
19:       int * itsWeight;
20:   };
21:
22:   SimpleCat::SimpleCat()
23:   {
24:       itsAge = new int(2);
25:       itsWeight = new int(5);
26:   }
27:
28:   SimpleCat::~SimpleCat()
29:   {
30:       delete itsAge;
31:       delete itsWeight;
32:   }
33:
34:   int main()
35:   {
36:       SimpleCat *Frisky = new SimpleCat;
37:       cout << Frisky is  << Frisky->GetAge() <<  years old\n;
38:       Frisky->SetAge(5);
39:       cout << Frisky is  << Frisky->GetAge() <<  years old\n;
40:       delete Frisky;
41:       return 0;
42:   }

Output:
Frisky is 2 years old
Frisky is 5 years old
Analysis: The class SimpleCat is declared to have two member variablesboth of which are pointers to integerson lines 18 and 19. The constructor (lines 2226) initializes the pointers to memory on the free store and to the default values.
The destructor (lines 2832) cleans up the allocated memory. Because this is the destructor, there is no point in assigning these pointers to null, because they will no longer be accessible. This is one of the safe places to break the rule that deleted pointers should be assigned to null, although following the rule doesn't hurt.
The calling functionin this case, main()is unaware that itsAge and itsWeight are pointers to memory on the free store. main() continues to call GetAge() and SetAge(),

 
< previous page page_153 next page >

If you like this book, buy it!