问题
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