2

Consider the following code:

#include <iostream>

class B {
   virtual void f() {
      std::cout << "Base" << '\n';
   }
};

class D final: public Base {
   void f() final override {
      std::cout << "Derived" << '\n';
   }
};

Paying attention to the two uses of the final contextual keyword above – available since C++11 – we can observe the following:

  • Adding final to D's member function f() prevents f() from being overridden in a class derived from D.
  • Adding final to the class D prevents it from further derivation.

Therefore, it is not possible that the member function f() is overridden by a class derived from D, since such a derived class can't exist due to the final applied to the class D.

Is there any point in using final as override control for a virtual member function of a class declared as final? Or is it merely redundant?

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • 1
    It's redundant, but this can be also seen for example when doing private inheritance, where all the members are rendered private; You still have the private keyword for some of them, but the private inheritance supersedes all. – Michael Chourdakis Jun 19 '19 at 19:37
  • Check out https://stackoverflow.com/questions/11704406/whats-the-point-of-a-final-virtual-function –  Jun 19 '19 at 19:40
  • 1
    "Adding final to the class D prevents it from further derivation." => " prevents it (f) from being overridden in a class derived from D". So it is redundant, no doubt. – Oliv Jun 19 '19 at 19:40
  • 1
    It seems to me that is redundant, in this case. As is redundant (if I'm not wrong) using `override` together with `final`. – max66 Jun 19 '19 at 19:42
  • @max66 because `final` already implies that the member function has to be `virtual`? – JFMR Jun 19 '19 at 19:49
  • I think the standard is clear, see http://eel.is/c++draft/class#4 and http://eel.is/c++draft/class.virtual#4 – Oliv Jun 19 '19 at 19:51
  • 1
    "because final already implies that the member function has to be virtual?" - Exactly. – max66 Jun 19 '19 at 20:53

1 Answers1

3

final on a virtual function in a final derived class is redundant.

Just like saying virtual on a method marked override is redundant. C++ just is that way sometimes.

AndyG
  • 39,700
  • 8
  • 109
  • 143