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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With