Łukasz Szcześniak
Łukasz Szcześniak

Reputation: 1444

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.

Upvotes: 0

Views: 913

Answers (2)

jfw
jfw

Reputation: 1

In windows there is little difference in inheriting from a parent with the common methods (could be abstract in the parent ) or implementing an interface (when again the behavior could be customized ). If you have an enumeration commonParticipant( cpPlayer, cpEnemy) then Windows allows access to the ultimate parent IUnknown and then down again to a child interface that identifies the methods peculiar to that child, i.e. you can pass an ICommonParticipant including the commonParticipant and then work with either a iPlayer or IEnemy interface

Upvotes: 0

Ken Bourassa
Ken Bourassa

Reputation: 6467

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.

Upvotes: 3

Related Questions