Board index » delphi » Q. Static variables in classes in Delphi?

Q. Static variables in classes in Delphi?

Say you want to know how many objects exist of a particular class. In C++
you can declare a class variable as static which means that one and only one
instance of this variable will exist no matter how many objects are
instantiated from the class.  Can you do this in Delphi, if not is there
another approach that will work.  Clearly I'd like to avoid any sort of
global variables if at all possible.

Any helpon this would be appreciated

Andy P

p.s. If you could cc: reply to A.Prem...@mmu.ac.uk  that would be extra nice

 

Re:Q. Static variables in classes in Delphi?


There is no such thing as static variable, but you can simulate this
behaviour, declaring such variable in the unit of your class (in the
implementation part) as typed constant. To access and to change it you
will need appropriate class methods (the same as static functions in
C++).

Hope it will help.

Re:Q. Static variables in classes in Delphi?


Andrew Premdas <A.PremdasNOS...@mmu.ac.uk> wrote in article
<EKK801....@exeter.ac.uk>...

Quote
> Say you want to know how many objects exist of a particular class. In C++
> you can declare a class variable as static which means that one and only
one
> instance of this variable will exist no matter how many objects are
> instantiated from the class.  Can you do this in Delphi, if not is there
> another approach that will work.  Clearly I'd like to avoid any sort of
> global variables if at all possible.

> Any helpon this would be appreciated

> Andy P

> p.s. If you could cc: reply to A.Prem...@mmu.ac.uk  that would be extra

nice

I don't think there is any such thing as a static class variable in Delphi.
 However there's nothing wrong with the 'Global Variable' approach as you
are quite free to keep your variable local to the unit implementing your
class by declaring it in the Implementation section.  For your Object
Instance Counter example, increment the Variable in your class constructor,
decrement it in the destructor and if necessary provide a class method to
allow users to read the variable value.

Cheers
Rich

Re:Q. Static variables in classes in Delphi?


   Thankyou to all those who replied, you've been ery helpful and it is
appreciated.

Andy P

Other Threads