Q: A class that contains a pointer variable as one of its data members should contain an overloaded assignment operator to prevent memory leaks.
I struggled with this question for a while. But finally chose false because of what and how the information was presented on pages 158, 159, and 160 regarding destructors and the overloaded assignment operator.
In the top paragraph of page 159, after discussing how a memory leak occurs on page 158, it says " ...we can put the necessary code in the destructor to ensure that when objectOne goes out of scope, the memory created by the pointer p is deallocated. This is one of the main purposes of including a destructor."
The bottom of page 159 states the information regarding the assignment operator and avoiding shallow copying of data for classes with a pointer data member, by overloading it. Because shallow copying has two pointers referencing the same data and when one goes out of scope the memory is deallocated but a pointer still points to it. That isn't a memory leak prevented with an overloaded assignment operator, because the memory has been deallocated.
A memory leak is memory staying allocated without any access to the data held in it. A destructor, with the necessary code, to ensure when an object goes out of scope the memory created by the pointer is deallocated prevents the memory leak.
I answered: False.
A destructor that has the necessary code to ensure when an object goes out of scope, the memory created by the pointer is deallocated, is what prevents the memory "leak." The overloaded assignment operator ensures that two objects pointing to the same data, has their own copy of the data, so if one goes out of scope and the memory is deallocated the other object isn't "pointing" at nothing, it is still pointing at its own copy of the data. But the destructor deallocating the memory when the object goes out of scope is what prevents a memory leak.