class has virtual functions and accessible non-virtual destructor
Asked Answered
T

4

25

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?

Trudietrudnak answered 29/4, 2011 at 4:5 Comment(0)
G
31

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;
}
German answered 29/4, 2011 at 4:9 Comment(1)
@Trudietrudnak It means it couldn't find an implementation of your destructor. Write a trivial one if you have nothing to actually destroy. A::~A() { } should do it.German
L
7

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

Lim answered 29/4, 2011 at 4:9 Comment(0)
R
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.

Regnal answered 10/5, 2012 at 12:50 Comment(1)
While I agree with this. Unfortunately GCC's warnings don't. I.e. it will still emit this warning when the destructor in the base class is declared protected.Breathing
C
2

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

Crass answered 29/4, 2011 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.