Presentation is loading. Please wait.

Presentation is loading. Please wait.

Destructor CSCE 121.

Similar presentations


Presentation on theme: "Destructor CSCE 121."— Presentation transcript:

1 Destructor CSCE 121

2 Destructor System automatically frees variables in a class when it is finished Kind of like a built in destructor, but not a good one if you use dynamic memory (i.e. the heap) Can be called explicitly (but rarely this way) If you want to know how, look it up! Normally called implicitly When an object goes out of scope on the stack When delete is called on a pointer to an object on the heap

3 Destruction Process (Automatic)
Object’s destructor function called Destructors called for each data member that is a class. Note pointers to a class are NOT a class; they are memory addresses. Destructors called for each base class. Basic data types are freed with the object. These include int, char, double, and any pointers. If a pointer refers to dynamic memory, the heap memory will be left behind. Memory Leak!!! This will make sense after we talk about inheritance!

4 Destructor Responsibility
Free any dynamic memory before the object’s memory is freed. In other words, call delete for any time new was called during the lifetime of the object. This is freeing resources in RAII.

5 Anatomy Destructor uses the Class name pre-pended by a tilde (~)
No parameters allowed. If you have to write one, then you are probably using ‘delete’ in it. Class LinkedList { LinkedList(); // constructor ~LinkedList(); // destructor }


Download ppt "Destructor CSCE 121."

Similar presentations


Ads by Google