This question already has an answer here:
- When to use virtual destructors? 16 answers
I am trying to understand who should have a virtual destructor and why.
class Person{
public
virtual ~Person(){
cout << "person destruction" << endl;
}
};
class Student: virtual public Person{
public:
~Student(){
cout << "destroying student" << endl;
}
};
//Faculty being a Faculty member
class Faculty: virtual public Person{
public:
~Faculty(){
cout << "destroying faculty" << endl;
}
};
class TA: public Student, public Faculty {
public:
~TA(){
cout << "destroying TA" << endl;
}
};
I understand that you cannot do polymorphic deletes. When I do something like:
//A - case when Person doesn't have a virtual destructor
Person *p = new Student();
delete p;
It crashes WHEN my base class doesn't have a virtual destructor. Makes sense. BUT when I do:
//B
Faculty *f = new TA();
delete f;
How come this does not crash? Why is this not analogous to the previous case? Faculty does not have a virtual destructor.
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire