Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Final specifier

Use case

Prevent overriding of security-critical methods.

Explanation

final on a method prevents derived classes from overriding it. final on a class prevents inheritance entirely.

Code

#include <iostream>

struct Validator {
  virtual bool validate() { return false; }
};

struct SignatureValidator : Validator {
  bool validate() override final { return true; }
};

struct ExtendedValidator : SignatureValidator {
  // cannot override 'final' function "SignatureValidator::validate"
  // bool validate() override {}
};

struct SecureValidator final : Validator {
  bool validate() override { return true; }
};

// a 'final' class type cannot be used as a base class
// struct ExtendedSecureValidator : SecureValidator {};

int main() {
  SignatureValidator v;
  std::cout << "Valid: " << std::boolalpha << v.validate() << "\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/final-specifier
Valid: true