Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi abstract class avoid implementation

Tags:

delphi

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

type
 TCableSPF = class abstract
  //code
end;

This is an abstract class of course and I have a lot of subclasses that implement it. By the way I see that is it possible to create an instance of this like;

a := TCableSPF.Create;

When I try to call its methods that are virtual and abstract I get the error and this is ok but can I prevent the creation of the class? Or Delphi allows this by default? thanks for the help

like image 478
Emma Rossignoli Avatar asked Feb 05 '23 09:02

Emma Rossignoli


1 Answers

The class abstract is a holdover from the Delphi for .Net days.
For reasons unknown there is no (current) implementation behind this keyword.

If you want to prevent instantiation 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 descendent object can access the constructor, other code cannot access the constructor.
Because you reintroducing the virtual constructor, you also cannot instantiate 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 should not declare the constructor override. Instead declare it virtual reintroduce (or just reintroduce if you don't want to allow virtual constructors).

like image 148
Johan Avatar answered Feb 15 '23 11:02

Johan