< previous page page_151 next page >

Page 151
Output:
SimpleCat Frisky
Constructor called.
SimpleCat * pRags = new SimpleCat..
Constructor called.
delete pRags
Destructor called.
Exiting, watch Frisky go
Destructor called.
Analysis: Lines 613 declare the stripped-down class SimpleCat. Line 9 declares SimpleCat's constructor, and lines 1519 contain its definition. Line 10 declares SimpleCat's destructor, and lines 2124 contain its definition.
In line 29, Frisky is created on the stack, which causes the constructor to be called. In line 31, the SimpleCat pointed to by pRags is created on the heap; the constructor is called again. In line 33, delete is called on pRags, and the destructor is called. When the function ends, Frisky goes out of scope, and the destructor is called.
Accessing Data Members
You accessed data members and functions by using the dot (.) operator for Cat objects created locally. To access the Cat object on the free store, you must dereference the pointer and call the dot operator on the object pointed to by the pointer. Therefore, to access the GetAge member function, you would write
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
(*pRags).GetAge();
Parentheses are used to assure that pRags is dereferenced before GetAge() is accessed.
Because this is cumbersome, C++ provides a shorthand operator for indirect access: the points-to operator (->), which is created by typing the dash (-) immediately followed by the greater-than symbol (>). C++ treats this as a single symbol. Listing 10.2 demonstrates accessing member variables and functions of objects created on the free store.
LISTING 10.2 ACCESSING MEMBER DATA OF OBJECTS ON THE FREE STORE

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:      // Listing 10.2
 2:      // Accessing data members of objects on the heap
 3:
 4:      #include <iostream.h>
 5:
 6:      class SimpleCat
 7:      {
 8:      public:
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_151 next page >

If you like this book, buy it!