IceCold
IceCold

Reputation: 21134

Creating a custom constructor without directly calling inherited

Is it ok if in my custom constructor I don't call directly inherited but instead I call the 'normal' constructor?

 TContainer = Class(TNGContainer)
  private
    FEncoding: TMyEncoding;
  protected
  public
    constructor Create;   overload;    override;
    constructor Create(Enc: TMyEncoding);  overload;
  end;


constructor TContainer.Create;     { 'normal' constructor }
begin
 inherited Create;
 Clear;
 BufMaxSeqLen       := 8*KB;
 FEncodingOffset    := 33;
 {More stuff to initialize here...}
end;


constructor TContainer.Create(Enc: TMyEncoding);    { New constructor }
begin
 Create;              { Call 'normal' constructor which will call Inherited }
 Encoding:= Enc;
end;

I could call inherited in the second constructor but the first constructor has lots of initialization code. So, I would have to duplicate this code in both constructors. It will be easy to modify the initialization code in one constructor and forget to do the same in the other constructor.

I ran the code line by line and the constructors are called in the correct order. The inherited (parent) constructor is called correctly.


Pieter B's comment made me ask this 'in conclusion' question: what makes constructor a constructor?
The fact that it starts with keyword constructor or the fact that it calls inherited (calling the constructor in the parent object)?

Upvotes: 4

Views: 170

Answers (1)

Disillusioned
Disillusioned

Reputation: 14832

Yes, it's perfectly acceptable. In fact, in this case calling inherited Create in your new constructor would be bad and expose you to a risk of subclass's overridden constructors not being called when they should.

Assuming a hierarchy: TSubContainer = class(TContainer) = class(TNGContainer):

As you've written it (which is correct) the sequence of steps would be as follows when your new constructor is called:

  • TContainer.Create(Enc: TMyEncoding);
  • TSubContainer.Create;
  • TContainer.Create; (assuming TSubContainer calls inherited)
  • TNGContainer.Create;

If you had instead called inherited Create, the sequence of steps would be as follows:

  • TContainer.Create(Enc: TMyEncoding);
  • TNGContainer.Create;

Note that any work that should be done in TSubContainer.Create; and TContainer.Create; will not happen.

Upvotes: 1

Related Questions