O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required