class has virtual functions and accessible non-virtual destructor

前端 未结 4 1269
-上瘾入骨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 07:53

    Give class A:

    virtual ~A() { }
    

    That way, derived classes such as B will still have their custom destructor called if you delete them via an A*.

    0 讨论(0)
  • 2020-12-15 08:03

    If a class has virtual functions then its destructor should be virtual as well. Yours has an accessible destructor but it is not virtual.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-15 08:09

    As thumb rule(IMHO) or in Short the destructor in the base class has to be either public and virtual or protected non virtual to prevent the memory leaks.by doing so the destructors of the derived class get called and this prevents the memory leakage whenever the Base pointer/reference holding derived address/reference is deleted.

    0 讨论(0)
提交回复
热议问题