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 ?
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.
There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With