Last modified on 27 July 2013, at 20:59

More C++ Idioms/Final Class

Final ClassEdit

IntentEdit

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

Also Known AsEdit

MotivationEdit

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 CodeEdit

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 destructor 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++11Edit

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 UsesEdit

Related IdiomsEdit

ReferencesEdit