ShiqiYu / CPP

Lecture notes, projects and other materials for Course 'CS205 C/C++ Program Design' at Southern University of Science and Technology.
2.07k stars 351 forks source link

Forget to explicitly define a virtual destructor in polymorphic base classes. #33

Open ltimaginea opened 2 years ago

ltimaginea commented 2 years ago

https://github.com/ShiqiYu/CPP/blob/14c70552862fffb0463e596607ff6f95dcd6d804/week12/examples/virtual.cpp#L5-L14 The class Person doesn't have a user-written virtual destructor, so its destructor defaults to public non-virtual.

https://github.com/ShiqiYu/CPP/blob/14c70552862fffb0463e596607ff6f95dcd6d804/week12/examples/virtual.cpp#L49-L51 The result of delete p; is undefined behavior, so it might call Person::~Person only and leak the string id .

In general, we should explicitly define a virtual destructor in polymorphic base classes. See C.127: A class with a virtual function should have a virtual or protected destructor .