mercredi 19 juin 2019

Why adding final to a member function of a final class?

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 it 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?

Aucun commentaire:

Enregistrer un commentaire