Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Base { public: virtual void exec(); virtual void exec(int) final; }; class Derived : Base { virtual void exec() override; }; class FinalClass final : Derived; |
Usage / Usability
- Override
- Can be used only on virtual functions that are declared in a base class. This assures that the function is overriden and not overwritten by mistake.
- Used to clearly express the intent that a given derived class function is meant to provide a new implementation for a base class function
- Helps the compiler flag errors where one accidentally overloads rather than overrides
- Final
- In functions: Used so that the function cannot be overridden anymore
- In classes: Used so that the class cannot be further derived from
PROS
- Express a clear image on what the programmer wanted to do.
CONS
- Adding final after a class or function is part of the function skeleton. In case we want to override it, we will break the compatibility with previous versions.
Quiz – Which lines will compile? (separately)
1 2 3 4 5 6 7 8 |
class Base { public: virtual void exec(); virtual void exec(int) final; virtual void exec(double) const; void exec(std::string); }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Derived : Base { void exec(); // 1 void exec() override; // 2 virtual void exec() override final; // 3 virtual void exec(int) override; // 4 virtual void exec(int) final; // 5 virtual void exec(double) override; // 6 virtual void exec(double) const; // 7 virtual void exec(double) override const; // 8 virtual void exec(double) const override final; // 9 virtual void exec(std::string) override; // 10 virtual void exec(std::string) final; // 11 }; |
Answer: All except 4, 6, and 10.