Search code examples
pascallazarusfreepascaldelphi

Pascal - Class inheritance between two different files?


Say I have two files, characters.pas and ogre.pas. An ogre is a character, but I'm trying to separate the two files for cleanliness sake. In characters.pas I have

unit Characters;

{$mode objfpc}{$H+}

interface
type
  TCharacter = class(TOBject)
    private
      // ...
    public
      // ...
    published
      // ...
  end;

implementation
  // Method bodies
end.

In ogre.pas I have

unit Ogre;

{$mode objfpc}{$H+}

interface
type
  TOgre = class(TCharacter)
    public
        constructor create; override;
    end;


implementation

constructor TOgre.create();
begin
  // Banana banana banana
end;
end.

Adding a uses block anywhere in either of the .pas files throws an error, which leads me to believe that all classes that rely on inheritance must be in the same file as their parents. Am I missing something?


Solution

  • Yes you miss something: the use section. You have to declare that unit Ogre uses unit Characters:

    unit Ogre;

    {$mode objfpc}{$H+}
    
    interface
    
    uses
      Characters;
    
    type
      TOgre = class(TCharacter)
        public
            constructor create; override;
        end;
    
    
    implementation
    
    constructor TOgre.create();
    begin
      // Banana banana banana
    end;
    end. 
    

    read more:

    Also note that if you want some fields to be visible from a TCharacter to a TOgre but still not accessible from the main program then you'll have to set their visibility to protected