IceCold
IceCold

Reputation: 21134

Using inherited in the "Create" constructor of an TObject

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;

Upvotes: 24

Views: 11601

Answers (4)

Toon Krijthe
Toon Krijthe

Reputation: 53366

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.

Upvotes: 13

Marcelo Rocha
Marcelo Rocha

Reputation: 43

I call it, except when i need a very optimized constructor.

Upvotes: 2

André
André

Reputation: 9112

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.

Upvotes: 3

Craig Stuntz
Craig Stuntz

Reputation: 126547

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.

Upvotes: 41

Related Questions