-
Notifications
You must be signed in to change notification settings - Fork 406
Open
Description
CPP/week12/examples/virtual.cpp
Lines 5 to 14 in 14c7055
| 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.
CPP/week12/examples/virtual.cpp
Lines 49 to 51 in 14c7055
| 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
Labels
No labels