The keyword final is defined in Java, and the class modified by final cannot be inherited.
In C ++, the constructor of the subclass automatically calls the constructor of the parent class. Similarly, the sub-class destructor automatically calls the parent class's destructor. If a class cannot be inherited, you only need to define its constructor and destructor as private functions. When a class tries to inherit from it, it will inevitably cause compilation errors because it tries to call constructor and destructor.
However, the constructor and destructor of this class are both private functions. How can we get the instances of this class? You can create and release a class instance by defining the static state. Based on this idea, you can write the following code:
FinalClass1* DeleteInstance( FinalClass1*= ~
This class cannot be inherited, but it is a little inconvenient to use because it is different from the general class. For example, you can only get instances on the stack, but not instances on the stack.
Can I implement a class with the same usage as a general class except that it cannot be inherited? There are always methods, but some skills are required. See the following code:
template <typename T> ~ FinalClass2 : MakeFinal<FinalClass2>~
This class is similar to a general class. You can create instances on the stack or stack. Although the constructors and destructor of the class MakeFinal <FinalClass2> are both private, because the class FinalClass2 is its friend function, therefore, calling MakeFinal <FinalClass2> constructor and destructor in FinalClass2 will not cause compilation errors.
However, if you try to inherit a class from FinalClass2 and create its instance, It is compiled differently.
Try : ~
Because the FinalClass2 class is inherited from the class MakeFinal <FinalClass2> virtual, when calling the Try constructor, it will directly skip FinalClass2 and directly call the MakeFinal <FinalClass2> constructor. Unfortunately, Try is not a friend of MakeFinal <FinalClass2>, so it cannot call its private constructor.
Based on the above analysis, classes that attempt to inherit from FinalClass2 will cause compilation errors once instantiated, so FinalClass2 cannot be inherited. This satisfies the design requirements.
The final keyword already exists in C ++ 11: it is used to prevent the virtual function of the specified class from being overwritten by the inheritance class of the class ), or specify a class to become a class that cannot be inherited (final class ).
foo(); C : B