Skip to content

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

@ltimaginea

Description

@ltimaginea

class Person
{
public:
string name;
Person(string n): name(n){}
virtual void print()
{
cout << "Name: " << name << endl;
}
};

The class Person doesn't have a user-written virtual destructor, so its destructor defaults to public non-virtual.

Person * p = new Student("xue", "2020");
p->print(); //if print() is not a virtual function, different output
delete p; //if its destructor is not virtual

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 .

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions