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.


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);
  vPlayer : TPlayer;
  vEnemy : TEnemy;
  if Source is TPlayer then
    vPlayer := TPlayer(Source);
    [Do whatever with vPlayer]
  end else if Source is TEnemy then
    vEnemy := TEnemy(Source);
    [Do Whatever with vEnemy]

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.

Need Your Help

android: Binary XML file line #9: error inflating class fragment

android api map

I was trying to show the maps in android application. I am using map V2. But the error "Binary XML file line #9: error inflating class fragment" is thrown. The app is crashed on launch.

Move image left to right continuously

ios animation nstimer

I need to make run this animation from left to right continuously. Now Is working, but show 1 time only (when the game is loaded). I want to make this animation run continously, left to right