< previous page page_186 next page >

Page 186
Listing 12.4 illustrates the danger of returning a reference to an object that no longer exists.
LISTING 12.4 RETURNING A REFERENCE TO A NONEXISTENT OBJECT

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:      // Listing 12.4
 2:      // Returning a reference to an object
 3:      // which no longer exists
 4:
 5:      #include <iostream.h>
 6:
 7:      class SimpleCat
 8:      {
 9:      public:
10:            SimpleCat (int age, int weight);
11:            ~SimpleCat() {}
12:            int GetAge() const { return itsAge; }
13:            int GetWeight() const { return itsWeight; }
14:     private:
15:           int itsAge;
16:           int itsWeight;
17:     };
18:
19:     SimpleCat::SimpleCat(int age, int weight):
20:     itsAge(age), itsWeight(weight) {}
21:
22:     SimpleCat &TheFunction();
23:
24:     int main()
25:     {
26:           SimpleCat &rCat = TheFunction();
27:           int age = rCat.GetAge();
28:           cout << rCat is  << age <<  years old!\n;
29:           return 0;
30:     }
31:
32:     SimpleCat &TheFunction()
33:     {
34:           SimpleCat Frisky(5,9);
35:           return Frisky;
36:     }

Output:
Compile error: Attempting to return a reference to a local object!

 
< previous page page_186 next page >

If you like this book, buy it!