class has virtual functions and accessible non-virtual destructor

不羁岁月 提交于 2019-12-18 03:24:26

问题


I have two classes:

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

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

B::B() {}

void B::somefunction() {
    //  some code
}

But with g++ I get errors:

class A has virtual functions and accessible non-virtual destructor
class B has virtual functions and accessible non-virtual destructor

I don't have any idea what this error is... Somewhere on blogs I read that it's a compiler warning. How can I fix the problem?


回答1:


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() = 0;
}



回答2:


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*.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/5827719/class-has-virtual-functions-and-accessible-non-virtual-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!