L2C
L2C

Reputation: 135

Delphi class variables

I have the following code:

// irrelevant code ...

type
  Zombie = class
  private
    ...
    Age : Integer;
    Alive : Boolean;
    TotalDeadZombies, TotalZombieAge : Double;
  public
    ...
    procedure ZombieGrow();
    procedure CheckIfDead();
    ...
    Function AvgLife() : Double;
  end;

procedure Zombie.ZombieGrow();
begin
  ...
  if (Alive = false) then
  begin
    TotalDeadZombies := TotalDeadZombies + 1;
    TotalZombieAge := TotalZombieAge + Age;
  end;
end;

procedure Zombie.CheckIfDead();
begin
  if Random(100) < 20 then
    Alive := False;
end;

function Zombie.AvgLife() : Double;
begin
  Result := TotalZombieAge / TotalDeadZombie;
end;

The problem I have is I want to display the average age of dead zombies. This would be done via something like :

Write('Average age '+Floattostr(Round(AvgLife)))

However, this is called in another class (not shown here), and from my understanding of OOP, it would require me to specify an instantiated object, e.g zombies[1].AvgLife if they were stored in, say, a Zombies[] array (just an example).

Is there a way of making it so the variables TotalDeadZombies and TotalZombieAge are not tied to any instantiated zombies, but rather to a class variable that I can then just call AvgLife somehow? Is it as simple as just making them global variables? Or can it be done another way?

Upvotes: 0

Views: 4517

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108938

You just have to declare the variables as class var; then they belong to the class, and not to a particular instance of a class.

type
  TZombie = class
  public
    class var TotalDeadZombies, TotalZombieAge: Double;
  end;

You can access these like TZombie.TotalDeadZombies. Similarly, there are class methods, class properties, etc.

Have a look at the official documentation.

Upvotes: 8

Related Questions