Sams Teach Yourself C++ in 21 Days

(singke) #1
24: SimpleCat & TheFunction();
25:
26: int main()
27: {
28: SimpleCat & rCat = TheFunction();
29: int age = rCat.GetAge();
30: std::cout << “rCat is “ << age << “ years old!” << std::endl;
31: std::cout << “&rCat: “ << &rCat << std::endl;
32: // How do you get rid of that memory?
33: SimpleCat * pCat = &rCat;
34: delete pCat;
35: // Uh oh, rCat now refers to ??
36: return 0;
37: }
38:
39: SimpleCat &TheFunction()
40: {
41: SimpleCat * pFrisky = new SimpleCat(5,9);
42: std::cout << “pFrisky: “ << pFrisky << std::endl;
43: return *pFrisky;
44: }

pFrisky: 0x00431C60
rCat is 5 years old!
&rCat: 0x00431C60

OUTPUT


284 Day 9


LISTING9.14 continued

This compiles, links, and appears to work. But it is a time bomb waiting to
go off.

CAUTION

TheFunction()in lines 39–44 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 41. The address that pointer holds is printed, and then the pointer is
dereferenced and the SimpleCatobject is returned by reference.
On line 28, the return of TheFunction()is assigned to a reference to SimpleCat, and
that object is used to obtain the cat’s age, which is printed on line 30.
To prove that the reference declared in main()is referring to the object put on the free
store in TheFunction(), the address-of operator is applied to rCat. Sure enough, it dis-
plays the address of the object it refers to, and this matches the address of the object on
the free store.

ANALYSIS
Free download pdf