Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ltimaginea opened this issue Feb 23, 2022 · 0 comments

Comments

@ltimaginea
Copy link

ltimaginea commented Feb 23, 2022

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 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant