Deleting Objects

When you call delete on a pointer to an object on the heap, 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 heap.

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


SimpleCat Frisky...
Constructor called.
SimpleCat * pRags = new SimpleCat..
Constructor called.
delete pRags...
Destructor called.
Exiting, watch Frisky go...
Destructor called.
					

Lines 4–11 declare the stripped-down class SimpleCat. On line 27, Frisky is created on the stack, which causes the constructor to be called. In line 30, 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.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.219.33