class has virtual functions and accessible non-virtual destructor

前端 未结 4 1274
-上瘾入骨i
-上瘾入骨i 2020-12-15 07:23

I have two classes:

class A {
public:
    virtual void somefunction() = 0;
};

class B : public A {
public:
    B();
    ~B();
    void somefunction();
};

B         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-15 08:05

    This happens because your base class A does not have a virtual destructor. For instance, if you had this code:

    int main()
    {
        A* a = new B;
        delete a;
    }
    

    Then the delete a call would not be able to call B's destructor because A's isn't virtual. (It would leak all of B's resources.) You can read more about virtual destructors here.

    Add a virtual destructor to your base class and you should be fine.

    class A
    {
    public:  
        virtual void somefunction() = 0;
        virtual ~A() = default;
    }
    

提交回复
热议问题