Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Class variable per class

I've added a class variables to the base class of a deep class hierarchy. It's an integer intended to count number of instances created per class type. But I've run into a problem.

Given the example:

  TBaseClass = class
  private
    class var fCreated: integer;
  public
    class function NewInstance: TObject; override;  
  end;

  TDescendant = class(TBaseClass)
  end;

  ...

  class function TBaseClass.NewInstance: TObject;
  begin
    result := inherited NewInstance;
    inc(fCreated);
  end;

I assumed that I can use the class var to store the number of instances created per class, but this does not seem to be the case.

Inspecting TBaseClass.fCreated returns same value as TDescendant.fCreated, changing one via inspector changes the other, so it behaves as if fCreated is a single global var.

I expected fCreated to be maintained per class type, isn't that the point ? What am I missing ?

like image 940
Daniel Maurić Avatar asked Jun 18 '12 11:06

Daniel Maurić


People also ask

How do you find the class variable within a class?

Accessing Class Variables We can access static variables either by class name or by object reference, but it is recommended to use the class name. Access inside the constructor by using either self parameter or class name. Access from outside of class by using either object reference or class name.

How many variables are in a class?

There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.

Can you declare variables in a class?

Typically, you declare a class's variables before you declare its methods, although this is not required. Note: To declare variables that are a member of a class, the declarations must be within the class body, but not within the body of a method. Variables declared within the body of a method are local to that method.

How are class variables used in class methods?

Variable defined inside the class: var_name. If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.


1 Answers

You are missing nothing. Your analysis of how class variables work is correct. A class var is nothing more than a global variable that is scoped by the class.

One simple solution for you is to use a dictionary to count the instances. A more hacky approach is to use a trick of mine that Hallvard Vassbotn blogged about, which (ab)uses the VMT to store class-specific fields. You can read all about it here.

like image 72
PatrickvL Avatar answered Oct 07 '22 02:10

PatrickvL