user2953119
user2953119

Reputation:

Is it safe to declare non-virtual destructor in the derived class

In the program:

struct A
{
    virtual ~A(){ }
};

struct B : A
{
    ~B(){ }
};
int main(){ }

The Standard N4296::12.4/9:

If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.

So, the compiler will redeclare the destructor in the struct B as a virtual on its own, right? Why are we permitted to declare such a destructor then? It may be a little confusing to another developer.

Upvotes: 1

Views: 118

Answers (2)

songyuanyao
songyuanyao

Reputation: 172884

Yes. Your understanding is right.

Why are we permitted to declare such a destructor then?

I agree with you that it's a little confused, but you can remove the virtuallity of the function of all the base and derived classes by just removing the virtual from the base class.

Upvotes: 1

timrau
timrau

Reputation: 23058

A function overriding a virtual member function is always virtual, no matter you declare virtual or not. Thus B::~B() is always virtual since A::~A() is virtual.

Upvotes: 5

Related Questions