Previous Section  < Free Open Study >  Next Section

Leak #2

Nested object pointers that are not cleaned up properly. A less obvious pitfall exists when one object contains another object by reference instead of by value. In the example code shown here, a Meal object contains a Melon object by reference (i.e., a Meal contains a pointer to a Melon). This Melon is dynamically allocated in the Meal's constructor and therefore must be deallocated in its destructor. The confusion occurs when a developer thinks that the Melon's destructor is called automatically by the Meal's destructor. Automatic destructor calls will occur when one object contains another by value. In our example, this would translate to a Meal object that contains a Melon object (i.e., by value).

    Previous Section  < Free Open Study >  Next Section