mardi 23 avril 2019

Multiple Inheritance and which destructors to make virtual? How come A is not allowed but B is? [duplicate]

This question already has an answer here:

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