Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function inheritance on Delphi error

Tags:

delphi

I would like to know why I'm having an "Incompatible Types" error message on the following code. The result I'm looking for to the TInheritanceClass is 'Test String Passed'.

TBaseClass = class
  function Test: String; virtual;
end;

TDerivedClass = class(TBaseClass)
  function Test: String; override;
end;

function TBaseClass.Test: String;
begin
  Result := Result + ' Passed';
end;

function TDerivedClass.Test: String;
begin
  Result := 'Test String';
  inherited;
end;
like image 468
HilarioSouza Avatar asked Sep 29 '26 01:09

HilarioSouza


1 Answers

function TInheritanceClass.Test: String;
begin
  Result := 'Test String';
  inherited;
end;

The statement inherited is appropriate when calling an inherited method for a procedure. For a function you would need to write:

Result := inherited;

or:

Result := inherited Test;

The base class method is also wrong. You wrote:

function TBaseClass.Test: String;
begin
  Result := Result + ' Passed';
end; 

It is a mistake to read a function result variable before initializing it. It looks like you are trying to pass data to the base class method via the function result variable. Whilst current implementation details mean that this might appear to work, it is a fairly gross violation of design principles. Do not attempt anything like this.

Probably you need a slightly more complex structure. Perhaps like this:

type
  TBaseClass = class
  public
    function TestName: string; virtual; abstract;
    function TestPassedText: string;
  end;

  TDerivedClass = class(TBaseClass)
  public
    function TestName: string; override;
  end;

function TBaseClass.TestPassedText: String;
begin
  Result := TestName + ' Passed';
end;

function TDerivedClass.TestName: String;
begin
  Result := 'MyName';
end;
like image 82
David Heffernan Avatar answered Oct 01 '26 17:10

David Heffernan