0

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?

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.