Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May a destructor be final?

Does the C++ standard allow a destructor to be declared as final? Like this:

 class Derived: public Base  {       ...       virtual ~Derived() final;  } 

And if so, does that prevent the declaration of a derived class:

 class FurtherDerived: public Derived {// allowed?  } 

If it is allowed, is a compiler likely to issue a warning? Is declaring a destructor to be final a workable idiom for indicating that a class is not intended to be used as a base class?

(There is no point in doing this in a ultimate base class, only a derived class.)

like image 997
Raedwald Avatar asked Nov 29 '17 15:11

Raedwald


People also ask

What is a final class in C++?

The final specifier in C++ marks a class or virtual member function as one which cannot be derived from or overriden.

Is virtual destructor inherited?

Yes, they are the same. The derived class not declaring something virtual does not stop it from being virtual. There is, in fact, no way to stop any method (destructor included) from being virtual in a derived class if it was virtual in a base class.

Does derived class need virtual destructor?

Do not delete an object of derived class type through a pointer to its base class type that has a non- virtual destructor. Instead, the base class should be defined with a virtual destructor. Deleting an object through a pointer to a type without a virtual destructor results in undefined behavior.


1 Answers

May a C++ destructor be declared as final?

Yes.

And if so, does that prevent declaration of a derived class:

Yes, because the derived class would have to declare a destructor (either explicitly by you or implicitly by the compiler), and that destructor would be overriding a function declared final, which is ill-formed.

The rule is [class.virtual]/4:

If a virtual function f in some class B is marked with the virt-specifier final and in a class D derived from B a function D​::​f overrides B​::​f, the program is ill-formed.

It's the derivation itself that is ill-formed, it doesn't have to be used.

Is declaring a destructor to be final a workable idiom for indicating that a class is not intended to be used as a base class?

Effectively, but you should just mark the class final. It's quite a bit more explicit.

like image 121
Barry Avatar answered Oct 09 '22 05:10

Barry