Must inherited be called on the first line?

WeG*_*ars 1 delphi

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;
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*nan 6

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

在调用继承的构造函数之前设置成员意味着如果继承的构造函数访问该成员,它将读取对派生构造函数的调用提供的值。虽然继承的构造函数不能直接访问该成员,但在这种情况下,它可以通过调用虚拟方法来访问它。但是请注意,从构造函数调用虚方法是一种有点可疑的做法,因为实例可能是部分构造的。