Implementing a class that cannot be inherited in C + + (example 1)
#include <iostream>using namespace std;template <typename t>class base{friend T;private:base () { cout << "base" << Endl; } ~base () {}};class b:virtual public base<b>{//must be aware that virtual inheritance public:b () {cout << ' B ' << end L }};class c:public b{public:c () {}//Inherit The times wrong, cannot compile};int main () {b b; Class B cannot be inherited//c C; return 0;}
The constructors and destructors for class base are private, only friends of the base class can be accessed, and Class B inherits the template's parameters for Class B, so the constructor of the parent class (Base) can be accessed directly when constructing Class B objects.
Why does it have to be virtual inheritance (virtual)?
See C++primer 4th 17th. Section 3.7 Special Initialization semantics
Usually each class initializes its own direct base class only, but when the virtual inheritance is changed, the virtual base class can be initialized multiple times, which is obviously not what we want. (example 2:aa,ab are derived classes of Class A, and then Class C inherits from AA and AB, if the previous method will cause C to be initialized two times, there will be two data)
To solve the problem of repeated initialization, classes that inherit from classes that have virtual base classes have special handling when initialized, and in virtual derivation, the virtual base class is initialized by the constructor of the lowest-level derived class. In our example 1 above, the constructor of C controls how the virtual base class is initialized.
Why can't class B be inherited?
Return to Example 1, because B is a friend of Base, so B objects can be created normally, but because B uses virtual inheritance, so if you want to create a C object, the C class constructor is responsible for the virtual base class (base) construction, but the constructor of the base is private, C does not have access to the permission (PS: Friend relationship cannot be inherited), so the C class in example 1 at compile time will be error. In this way, Class B cannot be inherited.
C + + Design a class that cannot be inherited, reason analysis