How to define a base class that should be inherited?

I created a component that it itself should never create, but instead it should be inherited. A similar concept for TThread . What can I do with this component to ensure that it is never created by itself without being inherited? For example, when an instance of an object is created, throw an exception in which the class should be inherited or, if possible, it does not even allow compiling any project where it is trying to execute an instance of this component base.

+6
source share
2 answers

This was mentioned in the TLama comments, but there was never an answer, so I will answer that.

 type TEvilClass = class public constructor Create; end; TGoodClass = class(TEvilClass) end; { TEvilClass } constructor TEvilClass.Create; begin if ClassType = TEvilClass then raise Exception.Create('I''m the evil class which cannot be instantiated!'); end; procedure TForm1.Button1Click(Sender: TObject); var EvilClass: TEvilClass; begin EvilClass := TEvilClass.Create; end; procedure TForm1.Button2Click(Sender: TObject); var GoodClass: TGoodClass; begin GoodClass := TGoodClass.Create; end; 

This script also makes sense to create your own exception type.

 type EvilClassException = Exception; TEvilClass = class(TComponent) public constructor Create(AOwner: TComponent); override; end; ... constructor TEvilClass.Create(AOwner: TComponent); begin inherited; if ClassType = TEvilClass then raise EvilClassException.Create('I''m the evil class which cannot be instantiated!'); end; 
+3
source

In XE2, you can declare a class abstract:

 type TMyclass = class abstract (TAncestor) 

Update: it seems that Delphi still allows you to create abstract classes (although the documentation for some versions says that it is not). The compiler should give a warning though.

Your class probably has some virtual method that needs to be overridden (and therefore should be inherited from). If so, just make the method abstract and you will get an exception when it is called in the base class.

+5
source

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


All Articles