41

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

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • 3
    The idiom for indicating that a class is not intended to be used as a base is to make that class final. – juanchopanza Nov 29 '17 at 15:30
  • 7
    If you intend to indicate that a class is not suitable to be a inherited from, you can just mark the whole class `final`. `class Devired final : public Base` – François Andrieux Nov 29 '17 at 15:30

1 Answers1

63

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • 14
    "...but you should just mark the class `final`". And [doing both would be redundant](https://stackoverflow.com/questions/43704769/is-the-final-function-specifier-redundant-when-using-the-final-class-specifier). – Raedwald Nov 29 '17 at 15:57