Disable Delphi class from implementation

In this question, you see that you can create an abstract class by adding keywrod abstract . I am translating a project in Delphi, but I see that it allows you to create an abstract class. This is the code:

 type TCableSPF = class abstract //code end; 

This is an abstract class, and I have many subclasses that implement it. By the way, I see that you can create an instance of this type:

 a := TCableSPF.Create; 

When I try to call its methods, which are virtual and abstract, I get an error, and this is normal, but can I prevent the class from being created? Or does Delphi allow this by default? thanks for the help

+5
source share
1 answer

class abstract is a delay with Delphi for .Net days.
For unknown reasons, there is no (current) implementation for this keyword.

If you want to prevent the creation of an instance of an abstract class, this keyword will not help. Instead, do the following:

 type TCableSPF = class abstract //code strict protected //Define all constructors for an abstract class as protected. constructor Create; virtual; reintroduce; end; 

By defining all constructors as protected, only the descendant object can access the constructor, other code cannot access the constructor. Since you re-enter the virtual constructor, you also cannot create it using:

 unit A; type TMyAbstractObject = class abstract(TObjectX) strict protected constructor Create; virtual; reintroduce; end; ... unit B; TMyClass = class of TObjectX; AbstractObjectInstance = TMyClass.Create; //Will not work for TMyAbstractObject 

Note that you must not declare an override constructor. Instead, declare it virtual reintroduce (or just reintroduce if you don't want to allow virtual constructors).

+7
source

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


All Articles