"final" class implementation in C ++

I tried to understand the implementation code of "final" in cpp:

Below is the code:

/* A program with compilation error to demonstrate that Final class cannot be inherited */ class Final; // The class to be made final class MakeFinal // used to make the Final class final { private: MakeFinal() { cout << "MakFinal constructor" << endl; } friend class Final; }; class Final : virtual MakeFinal { public: Final() { cout << "Final constructor" << endl; } }; class Derived : public Final // Compiler error { public: Derived() { cout << "Derived constructor" << endl; } }; int main(int argc, char *argv[]) { Derived d; return 0; } 

Output: compiler error

 In constructor 'Derived::Derived()': error: 'MakeFinal::MakeFinal()' is private 

In this, I could not understand the logic of actually inheriting the MakeFinal class. We could just inherit it (the makeFinal class) as public, and even then we would not be able to inherit it further (since the Makefile constructor is private, and only its class can be accessed only for this class).

Any pointer

+6
source share
1 answer

This will not work. Non-virtual base classes are always initialized by a class that is immediately derived from them. That is, if the script looks like this:

 class Final : public MakeFinal { public: Final() {} }; class Derived : public Final {}; 

then ctor Derived only initializes Final , which is fine ( Final has a public ctor). Final ctor then initializes the MakeFinal , which is also possible since Final is a friend.

However, the rule is different for virtual base classes. All virtual base classes are initialized by the ctor of the derived object itself. That is, when creating an instance of Final , it has Final ctor that initializes the MakeFinal . However, when trying to create an instance of Derived it must be the Derived ctor that initializes the MakeFinal . And this is not possible due to MakeFinal private ctor.

Also note that C ++ 11 introduced the Final keyword for classes (and virtual functions).

+11
source

Source: https://habr.com/ru/post/947617/


All Articles