CPP icon indicating copy to clipboard operation
CPP copied to clipboard

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

Open ltimaginea opened this issue 3 years ago • 0 comments

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 .

ltimaginea avatar Feb 23 '22 08:02 ltimaginea