1. Design a class that cannot be inherited
1 set the constructor to private
The subclass cannot access the constructor of the base class at this point, so the subclass will be created with an error (unable to access private members)
Class base_uninherit{
Private:
Base_uninherit () {}
Base_uninherit (const base_uninherit& RHS) {}
base_uninherit& operator= (const base_uninherit& RHS) {return *this;}
Public:
static base_uninherit* construct () { //Only in this way can you construct an object on the heap
base_uninherit* pb=new Base_uninherit ( );
return PB;
~base_uninherit ();
};
Class Derived_uninherit:public base_uninherit{
};
In this case, although the base class cannot be inherited, the base class cannot be initialized on the stack, only an object can be created on the heap in the form of a static method of the class.
2) Using friend class
First declare a secondary template base class, make its constructor private, and only the declared friend class can be accessed. All classes that inherit the base class in finalclass form can no longer be inherited. And Finalclass can be created on both the heap and the stack at the same time.
Template<typename t>
class base{
friend T;
Private:
Base () {}
~base () {}
};
Class Finalclass:virtual public base<finalclass>{public
:
Finalclass () {}
~finalclass () {}
} ;
2. How to ensure that objects can only be created on the heap
To set a destructor as private
C + + is a statically bound language, so all non-virtual functions must be parsed at compile time. Check for accessibility Even if it is a virtual function.
When an object is created on the stack, the object is automatically destructor, which requires the destructor to be accessible.
When an object is created on the heap, the timing of the destructor is controlled by the programmer, so the destructor is not necessarily required
So when the destructor is private, if you create an object on the stack, the compilation will complain
3, how to ensure that only on the stack to create objects
objects created on the heap are implemented by the new operator, so disabling the new operator makes operator new private so that the object cannot be created on the heap