Search code examples
lazarusfreepascal

Pascal passing object of inheritance class to procedure


I have types declared as:

TPlayer = class(TObject) 
TBullet = class(TObject) 
TEnemy = class(TObject)   

and objects:

Player: TPlayer;
PlayerBullets: Array[1..20] of TBullet;
Enemies: Array[1..20] of TEnemy;
EnemyBullets: Array[1..20] of TBullet;

Now I want to create TBullet constructor, which can process informations from both Player and Enemies. In short, I want this constructor to handle both TPlayer and TEnemy objects.

My idea is:

constructor TBullet.Create(const Source: TObject);

Sadly it does not work. How to do this?

EDIT: My exact problem is: when I pass TPlayer or TEnemy object to this constructor it doesn't see atributes of those objects. For example: TPlayer has attr xPos. If I use Bullet.Create(Player) and in TBullet.Create I use Source.xPos I get an error.


Solution

  • I can think of 3 ways to achieve that.

    1. Have TPlayer and TEnemy both derive from the same base class that have all the information TBullet's constructor need, and have the constructor parameter of that type.
    2. Define an interface contains all the information needed by TBullet and have TPlayer and TEnemy implement that interface
    3. Leave everything "as is" and manage the different class in a "hard coded" manner in TBullet's constructor.

    By that I mean:

    constructor TBullet.Create(const Source: TObject);
    var 
      vPlayer : TPlayer;
      vEnemy : TEnemy;
    begin
      if Source is TPlayer then
      begin
        vPlayer := TPlayer(Source);
        [Do whatever with vPlayer]
      end else if Source is TEnemy then
      begin
        vEnemy := TEnemy(Source);
        [Do Whatever with vEnemy]
      end;
    end;
    

    Which solution is the best? That could be a debate in itself and largely dependant on your specific situation. Based solely on the name of your class, I'd guess option 1 could be valid. A "TCharacter" class could be created and use as a base calss for both TCharacter and TEnemy. But this is mere speculation at this point.