Jump to content
aehimself

Overloads in implementation

Recommended Posts

Hello,

 

We just met a strange issue and was wondering if anyone can explain why it is happening. The below code throws a stack overflow, as the compiler doesn't make a difference between TDateTime and Integer and keeps calling the first method:

 

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.DateUtils;

function GetDay(dt: TDateTime): string; Overload;
begin
  Result := GetDay(DayOfTheWeek(dt));
end;

function GetDay(i: Integer): string; Overload;
const LDays: array[1..7] of string = ('H', 'K', 'S', 'C', 'P', 'S', 'V');
begin
  Result := LDays[I];
end;

begin
  WriteLn(GetDay(Today));
end.

It works perfectly if you turn it to a dummy class and publish these methods as class functions:

Type
  x = Class
    class function GetDay(dt: TDateTime): string; Overload;
    class function GetDay(i: Integer): string; Overload;
  End;

It also works if you push these two methods in a separate unit with proper Interface section:

unit Unit1;

interface

function GetDay(dt: TDateTime): string; overload;
function GetDay(i: Integer): string;  overload;

implementation

I guess it'll have something to do on how overloads are interpreted in the implementation area...? Delphi 10.4, 10.4.2 and 11 are producing the same symptom.

Share this post


Link to post

The reason is that 

function GetDay(dt: TDateTime)

doesn't yet know about the other overload. You either have to replace their order or, better, add a definition like you did when you added their definition in the interface section of the unit.

Edited by Der schöne Günther
  • Thanks 1

Share this post


Link to post

Nothing strange at all but standard pascal behavior - compiler only sees what has been declared so far.

 

 

Possible solutions:

- change implementation order

- declare in separate unit interface part

- use forward

  • Like 1
  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×