default override of virtual destructor

前端 未结 7 1046
孤独总比滥情好
孤独总比滥情好 2021-02-01 12:50

Everyone knows that the desructor of base class usually has to be virtual. But what is about the destructor of derived class? In C++11 we have keyword \"override\" and ability t

7条回答
  •  野性不改
    2021-02-01 13:11

    The CPP Reference says that override makes sure that the function is virtual and that it indeed overrides a virtual function. So the override keyword would make sure that the destructor is virtual.

    If you specify override but not = default, then you will get a linker error.

    You do not need to do anything. Leaving the Child dtor undefined works just fine:

    #include 
    
    struct Notify {
        ~Notify() { std::cout << "dtor" << std::endl; }
    };
    
    struct Parent {
        std::string a;
        virtual ~Parent() {}
    };
    
    struct Child : public Parent {
        std::string b;
        Notify n;
    };
    
    int main(int argc, char **argv) {
        Parent *p = new Child();
        delete p;
    }
    

    That will output dtor. If you remove the virtual at Parent::~Parent, though, it will not output anything because that is undefined behavior, as pointed out in the comments.

    Good style would be to not mention Child::~Child at all. If you cannot trust that the base class declared it virtual, then your suggestion with override and = default will work; I would hope that there are better ways to ensure that instead of littering your code with those destructor declarations.

提交回复
热议问题