< previous page page_150 next page >

Page 150
Deleting Objects
When you call delete on a pointer to an object on the free store, that object's destructor is called before the memory is released. This gives your class a chance to clean up, just as it does for objects destroyed on the stack. Listing 10.1 illustrates creating and deleting objects on the free store.
LISTING 10.1 CREATING AND DELETING OBJECTS ON THE FREE STORE

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:     // Listing 10.1
 2:     // Creating objects on the free store
 3:
 4:     #include <iostream.h>
 5:
 6:     class SimpleCat
 7:     {
 8:     public:
 9:            SimpleCat();
10:             ~SimpleCat();
11     private:
12             int itsAge;
13     };
14
15     SimpleCat::SimpleCat()
16     {
17         cout << Constructor called.\n;
18         itsAge = 1;
19     }
20
21     SimpleCat::~SimpleCat()
22     {
23         cout << Destructor called.\n;
24     }
25
26     int main()
27     {
28         cout << SimpleCat Frisky\n;
29         SimpleCat Frisky;
30         cout << SimpleCat *pRags = new SimpleCat\n;
31         SimpleCat * pRags = new SimpleCat;
32         cout << delete pRags\n;
33         delete pRags;
34         cout << Exiting, watch Frisky go\n;
35         return 0;
36     }

 
< previous page page_150 next page >

If you like this book, buy it!