A final class (also known as a leaf class) is a class that permanently forbids derived classes. A class should be declared final only if the designers have decided to permanently forbid any future classes from deriving from the final class. A class should not be declared final merely because it doesn't happen to have any derived classes in the current application. An example follows. class Shape { //... }; /*final*/ class Circle : public Shape { //... }; C++ doesn't support a keyword for "final," so a comment is typically used. This means that the finality of a class is enforced by code reviews rather than by the compiler. However, it is not hard to get the compiler to enforce the class's finality: simply make the constructors private: and provide public: static create() member functions (the named constructor idiom; see FAQ 16.08). This will prevent derived classes from existing since the derived class wouldn't be able to call the (private:) constructor of the final class. A final class should not have any protected: data members all its data members should be private:. Similarly, a final class should not declare any new virtual functions (though it often overrides inherited virtual functions). Caution should be used before declaring a class to be final. Nonetheless, doing so is sometimes useful, as demonstrated in FAQ 33.12. |