This is probably a simple question, but i would like to know how to ensure a class’ constructor is called.
If i have the following code:
type TMyObject = class(TObject)
public
constructor Create;override;
end;
implementation
constructor TMyObject.Create;override;
begin
inherited;
//do other instantiation
end;
Delphi does not allow this – ‘Cannot override a static method’.
What i would like to do is ensure that the object is created using my custom Create constructor AND prohibiting calling the ancestors Create constructor.
My current solution to the problem is to define a uniquely signatured Create constructor like so:
constructor Create(aName : String);overload;
but the programmer could potentially call the ancestors Create() method.
You simply re-introduce a constructor with the ancestor’s name. Once you do that, there’s no way for the user to create a
TMyObjectcalling the constructor introduced inTObject. If you use code like this:You don’t use the
overridemodifier onTMyObject.Createbecause the ancestor’s constructor is not virtual.Using this scheme it is impossible for the user to create your
TMyObjectusing a constructor introduced in an ancestor. In this case, the ancestor isTObject, and the only constructor it has isTObject.Create. If the user writes this code:it’s quite obvious,
TMyObject‘s constructor would be called, not the one introduced inTObject.If you’re afraid users would jump through hoops in order to create your class using ancestor’s constructor, you can do your stuff from the
AfterConstructionmethod. That’s a virtual method, so it gets called even if your object is created using a class reference of an ancestor’s type: