Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a base class which must be inherited?

I have created a component which its self should never be instantiated, but instead it must be inherited. Similar concept to the TThread. What can I do to this component to ensure it's never instantiated by its self without being inherited? For example, when the object is instantiated, raise an exception that the class is required to be inherited, or if possible, don't even let any project compile where an instance of this component base is attempted.

like image 341
Jerry Dodge Avatar asked Nov 02 '13 22:11

Jerry Dodge


2 Answers

In XE2, you can declare the class as abstract:

type TMyclass = class abstract (TAncestor)

Upd: it seems that Delphi still allows creating abstract classes (although documentation for some versions says it doesn't). Compiler should give a warning though.

Probably your class has some virtual method that has to be overridden (and that's why it must be inherited from). If so, just make the method abstract, and you will get an exception when it's invoked in the base class.

like image 81
nullptr Avatar answered Nov 15 '22 08:11

nullptr


This was mentioned in the comments by TLama, but was never made an answer, so I'll answer this.

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 scenario is also one which 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;
like image 21
Jerry Dodge Avatar answered Nov 15 '22 09:11

Jerry Dodge