< previous page page_188 next page >

Page 188
LISTING 12.5 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
11:            int GetWeight() const { return itsWeight; }
12:
13:      private:
14:           int itsAge;
15:           int itsWeight;
16:     };
17:
18:     SimpleCat::SimpleCat(int age, int weight):
19:     itsAge(age), itsWeight(weight) {}
20:
21:     SimpleCat & TheFunction();
22:
23:     int main()
24:     {
25:           SimpleCat & rCat = TheFunction();
26:           int age = rCat.GetAge();
27:           cout << rCat is  << age <<  years old!\n;
28:           cout << &rCat:  << &rCat << endl;
29:           // How do you get rid of that memory?
30:           SimpleCat * pCat = &rCat;
31:           delete pCat;
32:           // Uh oh, rCat now refers to ??
33:           return 0;
34:     }
35:
36:     SimpleCat &TheFunction()
37:     {
38:           SimpleCat * pFrisky = new SimpleCat(5,9);
39:           cout << pFrisky:  << pFrisky << endl;
40:           return *pFrisky;
41:     }

Output:
pFrisky: 0x00431CA0
rCat is 5 years old!
&rCat: 0x00431CA0
This compiles, links, and appears to work. But it is a time bomb waiting to go off.

Analysis: The function TheFunction() has been changed so that it no longer returns a reference to a local variable. Memory is allocated on the free store and assigned to a pointer on line 38. The address that pointer holds is printed, and then the pointer is dereferenced and the SimpleCat object is returned by reference.

 
< previous page page_188 next page >

If you like this book, buy it!