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.\n"; 16: itsAge = 1; 17: } 18: 19: SimpleCat::~SimpleCat() 20: { 21: std::cout << "Destructor called.\n"; 22: } 23: 24: int main() ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.