8.3 Destructors PDF

Title 8.3 Destructors
Course Intermediate Programming Methodologies in C++
Institution De Anza College
Pages 4
File Size 117.8 KB
File Type PDF
Total Downloads 85
Total Views 156

Summary

A destructor is a special member feature of a class that is automatically called when a variable of that class type is destroyed. Class objects in C++ often use dynamically allocated data, which is then deallocated by the destructor.

When adding objects to a linked list, for example, th...


Description

8.3 Destructors 8.3 Destructors Destructor — special member function that is called automatically when a variable of that class is destroyed. C objects use dymically allocated data that is destroyed by destructor. Ex: A linked list class dynamically allocates nodes when adding items to the list. Without a destructor, the link list's nodes are not deallocated. The linked list class destructor should be implemented to deallocate each node in the list. Bad example of dealloc memory class LinkedListNode { public: ... int data; LinkedListNode* next; }; class LinkedList { public: ... LinkedListNode* head; }; int main() { LinkedList* list1; list1 = new LinkedList(); ... // Add items to list1 delete list1; //deletes head pointer only, not elements }

QUESTIONS 1 Using the delete operator to deallocate a LinkedList object automatically frees all nodes allocated by that object. FALSE 2 A destructor for the LinkedList class would be implemented as a LinkedList class member function. TRUE

3 If list1 were declared without dynamic allocation, as shown below, no destructor would be needed. FALSE. Even if the list itself isn't dynamically allocated, the list's nodes are. A destructor is still needed to free each node in the list.

Implementing the LinkedList class destructor destructors declared as: ~LinkedListNode(); ~LinkedList();

The LinkedList class destructor is implemented to free each node in the list. The LinkedListNode destructor is not required, but is implemented below to display a message when a node's destructor is called. Using delete to free a dynamically allocated LinkedListNode or LinkedList will call the object's destructor. #include using namespace std; class LinkedListNode { public: LinkedListNode(int dataValue) { cout...


Similar Free PDFs