Is it possible in Delphi to have a class method invoke an inherited instance method with the same name? For example, I tried something like this:
//... Skipped surrounding class definitions function TSomeAbstractDialogForm.Execute: Boolean; begin Result := ShowModal = mrOk; end;
I had a couple of specialized dialog classes that inherited the abstract dialog form, and each class had its own factory method:
class function TSomeInheritingDialogForm.Execute: Boolean; var Fm: TSomeInheritingDialogForm; begin Fm := TSomeInheritingDialogForm.Create(nil); try Result := Fm.Execute; finally Fm.Free; end end;
This approach resulted in a never ending loop since F.Execute, instead of invoking the intended instance method of the base class, kept calling the factory method over and over again (resulting in a pile of created forms).
Of course, the obvious solution was to change the name of the factory method (I named it CreateAndShow), but it made me curious. How come the compiler didn’t warn me about the hidden method? And is there a way to explicitly invoke the instance method in a situation like this?
You can try a hard cast. But it is better to rename the class function. (For example to CreateAndExecute).
The Execute in the child class hides the execute in the parent class (I think the compiler will give a warning for that). You can access this with a hard cast. But there is no way to distinguish between an instance method and a class method.