More C++ Idioms/Final Class

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Final Class
[edit | edit source]

Intent[edit | edit source]

  • Partially simulate the final class feature found in C++11 and other languages.
  • Partially prevent a class from further subclassing or inheritance.

Also Known As[edit | edit source]

  • Sealed Class

Motivation[edit | edit source]

Class designers may want to enforce that a specific class can not be further extended or subclassed by the user of the class. Other object-oriented languages such as Java and C# provide this feature to the class designers. In Java the keyword is called final whereas in C#, it is called sealed. Final class idiom is a way of partially simulating this effect in C++.

Solution and Sample Code[edit | edit source]

Final class idiom makes use of virtual inheritance and a friend class to create the effect of a final class. The idiom depends on the following C++ rule: the constructor (and destructor) of a virtually inherited class is called directly by the derived-most class. If access to the constructor or destructor of such a virtually inherited class is prevented, the class can not be subclassed further.

class MakeFinal
  MakeFinal() {}  // private by default.
  friend class sealed;

class sealed : virtual MakeFinal
{ };

class test : public sealed
{ };

int main (void)
  test t; // Compilation error here.

In the above example, the test class inherits from the sealed class and the main function tries to instantiate an object of type test. The instantiation fails because the test class can not access the private constructor of the MakeFinal class because it is defined private and inherited virtually. However, friendship is not inheritable and therefore, objects of type test can't be created.

Note that the said error occurs only when the test class is instantiated. This behavior is different from how final classes behave in Java and C#. In fact, this idiom does not prevent inheritance of static methods defined in the sealed class. As long as the test class is not instantiated and it accesses only the static members of the sealed class, compiler does not complain.

C++11[edit | edit source]

The C++11 standard provides the final modifier, which can be used to prevent a class from being subclassed.

class Base final { };

class test : public Base { };  // incorrect

Known Uses[edit | edit source]

Related Idioms[edit | edit source]

References[edit | edit source]