Understanding Pointers 239
25: cout << “Destructor called. “ << endl;^8
26: }
27:
28: int main()
29: {
30: cout << “SimpleCat Frisky... “ << endl;
31: SimpleCat Frisky;
32: cout << “SimpleCat *pRags = new SimpleCat...” << endl;
33: SimpleCat * pRags = new SimpleCat;
34: cout << “delete pRags... “ << endl;
35: delete pRags;
36: cout << “Exiting, watch Frisky go... “ << endl;
37: return 0;
38: }
SimpleCat Frisky...
Constructor called.
SimpleCat *pRags = new SimpleCat..
Constructor called.
delete pRags...
Destructor called.
Exiting, watch Frisky go...
Destructor called.
Lines 8–15 declare the stripped-down class SimpleCat. Line 11 declares
SimpleCat’s constructor, and lines 17–21 contain its definition. Line 12 declares
SimpleCat’s destructor, and lines 23–26 contain its definition. As you can see, both the
constructor and destructor simply print a simple message to let you know they have been
called.
On line 31,Friskyis created as a regular local variable, thus it is created on the stack.
This creation causes the constructor to be called. On line 33, the SimpleCatpointed to
by pRagsis also created; however, because a pointer is being used, it is created on the
heap. Once again, the constructor is called.
On line 35,deleteis called on the pointer,pRags. This causes the destructor to be called
and the memory that had been allocated to hold this SimpleCatobject to be returned.
When the function ends on line 38,Friskygoes out of scope, and its destructor is called.
Accessing Data Members ....................................................................................
You learned on Day 6, “Understanding Object-Oriented Programming,” that you
accessed data members and functions by using the dot (.) operator. As you should be
aware, this works for Catobjects created locally.
OUTPUT
LISTING8.5 continued
ANALYSIS