Sams Teach Yourself C++ in 21 Days

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

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

282 Day 9


This program won’t compile on the Borland compiler. It will compile on
Microsoft compilers; however, it should be noted that it is a poor coding
practice.

CAUTION
Free download pdf