Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

final
keyword
c++
communitycreator

What is a final specifier in C++?

Danil

final is a specifier introduced in C++11 that disallows overriding a member function when used in the declaration or definition of a virtual member function:

struct A {
  virtual void foo();
};

struct B: A {
  void foo() final; // Now foo can't be overriden in derived classes of B
  void bar() final; // Error: bar can't be final as is is non-virtual
};

struct C: B {
  void foo(); // Error: foo can't be overriden as it is final in B
};

It also disallows deriving from the class when used in a class definition:

struct Base { };

struct Derived final: Base { };

struct MyClass: Derived { };
// ^ Error: Derived is final

The final identifier is not reservedonly has special meaning when used in a member function declaration or class head and may be used to name objects and functions:

#include <iostream>
using namespace std;

int final(int a) {
  return a * 2;
}

int main() {
  int final = ::final(5);
  std::cout << "final(5) = " << final << '\n';
  return 0;
}

RELATED TAGS

final
keyword
c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring