Search code examples
delphiunicodeabstractbackwards-compatibility

Delphi abstract function calls with different name than base class


Say I've got a function

function GetFieldName(FieldIndex: Integer; FieldName: PChar; 
    Len: Integer): Integer; virtual; abstract;

and I'm trying to add

function GetFieldNameA(FieldIndex: Integer; FieldName: PAnsiChar; 
    Len: Integer): Integer;

Which will temporarily bridge my database connection for unicode.

I want to continue to call GetFieldName, make it not abstract, and do some bit typecasting to call GetFieldNameA, which will become a technically abstract version of the first GetFieldName. (I don't want to change the base class at all)

Is there a way, like adding the 'name' keyword for external references, to have an abstract function with a different name in the subclass?

What I'm imagining ending up with is something like:

function GetFieldName(FieldIndex: Integer; FieldName: PChar; 
    Len: Integer): Integer; 
function GetFieldNameA(FieldIndex: Integer; FieldName: PAnsiChar;
    Len: Integer): Integer name 'GetFieldName Virtual Abstract'; 

Solution

  • No, you can't do what you're proposing.

    Instead, override GetFieldName. Have it convert the PChar to a PAnsiChar (if necessary) before calling GetFieldNameA. The latter doesn't have to be (and can't, actually) be marked override. It can be an ordinary non-virtual function.

    The unfortunate part of that suggestion is that you'd have to do it in every descendant class. The alternative is to add a virtual abstract GetFieldNameA to the base class and then change all the descendants to override that instead of GetFieldName. Change GetFieldName in the base class to call GetFieldNameA. But that's a non-starter if you can't change the base class.