Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
532 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...