Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inherited in the "Create" constructor of an TObject

Tags:

delphi

Rant: Should I call "inherited" in the constructor of a class derived from TObject or TPersistent?

constructor TMyObject.Create;
begin
 inherited Create;   // Delphi doc: Do not create instances of TPersistent. Use TPersistent as a base class when declaring objects that are not components, but that need to be saved to a stream or have their properties assigned to other objects.    
 VectorNames := TStringList.Create;
 Clear;
end;
like image 293
Server Overflow Avatar asked Apr 21 '09 12:04

Server Overflow


3 Answers

Yes. It does nothing, true, but it's harmless. I think there is value in being consistent about always calling the inherited constructor, without checking to see if there is, in fact, an implementation. Some will say that it's worth calling inherited Create because Embarcadero might add an implementation for TObject.Create in the future, but I doubt this is true; it would break existing code which does not call inherited Create. Still, I think it is a good idea to call it for the reason of consistency alone.

like image 52
Craig Stuntz Avatar answered Nov 18 '22 22:11

Craig Stuntz


I always do this.

If you are refactoring and move code to a common ancestor, calling the inherited Create has the following advantages:

  1. If the common ancestor has a constructor, you can't forget to call it.
  2. If the common ancestor has a constructor with different parameters, the compiler warns you for this.
like image 38
Toon Krijthe Avatar answered Nov 18 '22 23:11

Toon Krijthe


You can also override "procedure AfterConstruction". This procedure is always called, no matter what kind of constructor.

public
  procedure AfterConstruction; override;
end;

procedure TfrmListBase.AfterConstruction;
begin
  inherited;
  //your stuff, always initialized, no matter what kind of constructor!
end;

For example: if you want to create an object with a different constructor than the normal TObject.Create, such as TComponent.Create(AOwner) or a custom (overloaded) constructor, you can get problems because your override is not called and (in this case) your "VectorNames" variable will be nil.

like image 3
André Avatar answered Nov 19 '22 00:11

André