Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an overload in child class

I have a base class TParent which defines a method without the overload directive:

  TParent = class
  public
    procedure Test();
  end;

In a child class TChild, I'm trying to add an overload for the Test procedure.

  TChild = class(TParent)
  public
    procedure Test(AParam : Integer);
  end;

On compiling there are no errors neither warnings but if I try to use the TParent.Test with a TChild instance, it gives an E2035 error, like if the parent method was hidden by the child's one:

var
  Obj : TChild;
begin
  Obj := TChild.Create;
  try
    Obj.Test();
  finally
    Obj.Free;
  end;
end;

[dcc32 Error] Unit1.pas(52): E2035 Not enough actual parameters

In order to resolve the compiling error, I have to add the overload directive to the TChild.Test declaration.

  TChild = class(TParent)   
  public
    procedure Test(AParam : Integer); overload;
  end;

It compiles and seems to work, but is it correct even if the TParent.Test declaration has no overload directive at all? Or should I change the name of the child's procedure in case the parent class has not predicted the method to be overloaded?

like image 826
Fabrizio Avatar asked Jun 11 '20 09:06

Fabrizio


1 Answers

I believe this is perfectly OK.

The documentation on overloading methods (as opposed to simply overloading non-method procedures and functions) states

A method can be redeclared [in a descendant class (my remark)] using the overload directive. In this case, if the redeclared method has a different parameter signature from its ancestor, it overloads the inherited method without hiding it. Calling the method in a descendent class activates whichever implementation matches the parameters in the call.

This is the only description given, and it isn't crystal clear. Still, the most reasonable interpretation is that it is perfectly fine to do what you suggest. The fact that it works and is used in a lot of existing Delphi source code I think settles it.

like image 140
Andreas Rejbrand Avatar answered Oct 24 '22 01:10

Andreas Rejbrand