Destructor CSCE 121 Destructor System automatically frees variables
Destructor CSCE 121
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
Destruction Process (Automatic) 1. Object’s destructor function called 2. Destructors called for each data member that is a class. • Note pointers to a class are NOT a class; they are memory addresses. 3. Destructors called for each base class. • Basic data types are freed with the object. This wil l make s after we ense talk abo ut inher itance! • These include int, char, double, and any pointers. • If a pointer refers to dynamic memory, the heap memory will be left behind. • Memory Leak!!!
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.
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 Linked. List { Linked. List(); // constructor ~Linked. List(); // destructor }
- Slides: 5