IceCold
IceCold

Reputation: 21134

Must inherited be called on the first line?

I have seen a piece of code like this (not mine). The author sets FField on the first line in the constructor before calling inherited. I am curious if this code valid.

TTest = class(TBaseObject, ITest)
    private
    protected
        FField: TObject;  
    end; 


constructor TTest.Create(aField: TObject);
begin
    FField:= aField;
    inherited Create();
    ...
end;

I think the memory for FField was already allocated and nilled at that point. Right?

Upvotes: 1

Views: 116

Answers (1)

David Heffernan
David Heffernan

Reputation: 612854

The code is valid. By the time your constructor runs, the instance has been allocated and default initialised.

Setting a member before calling the inherited constructor means that if the inherited constructor accesses that member, it will read the value provided by the call to the derived constructor. Whilst the inherited constructor cannot directly access the member, in this case, it could access it by calling a virtual method. Note, however, that calling virtual methods from constructors is a somewhat dubious practice, because the instance may be partially constructed.

Upvotes: 6

Related Questions