alvaroc
alvaroc

Reputation: 469

How to overload a Delphi class function

I have a Delphi (2007) class function like this:

Class Function InitGlobal : TForm; Overload; Virtual; Abstract;

in some descendant class I try to:

Class Function InitGlobal : TDescendentForm; Overload; Override;

But Delphi complains that TDescendentForm.InitGlobal differs from the previous declaration (despite the pressence of the "Overload" directive).

I guess that function result types can not be overloaded. Which is the correct way of define such overloading if any?

I checked Function overloading by return type?, but it mentions the cons and pros of making such overloading with no mention to Delphi.

Upvotes: 1

Views: 3700

Answers (1)

David Heffernan
David Heffernan

Reputation: 613602

Function overloading can only be based on parameters, and not on return values. There is no way for you to have two overloads that differ only in their return value.

What's more, even if you could do that, you are attempting to use override, and change the function's signature. That is also impossible. An override must have an identical signature to the function being overridden.

What you can do is override the function, and keep the same signature. You can remove the overload directive. Then your derived function would look like this:

class function InitGlobal: TForm; override;

Now, there is nothing to stop you returning an instance of TDescendentForm. That is still a TForm. What you would be doing here is returning a more a derived type at runtime.

The implementation might look like this:

Result := TDescendentForm.Create(...);
// compile time type of Result is TForm, but that is assignment compatible
// at run time with an instance of TDescendentForm

Upvotes: 3

Related Questions