7

In my class, i need to use a static variable ( static int next_id; in C++)

I use

private
    class var next_id: Integer;

I get Error : PROCEDURE or FUNCTION expected. How to declare some variable with Delphi 5 ?

RRUZ
  • 134,889
  • 20
  • 356
  • 483

3 Answers3

7

In Delphi 5, you can't. No class vars in Delphi 5 yet.

The next best thing is a global variable in the implementation section of the unit, though.

unit Whatever;

...

implementation

var
  next_ID: Integer;

...

initialization
  next_ID := 0;

end.

Or alternatively, at the very bottom:

begin
  next_ID := 0;
end.
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
  • Thank you ..It's possible to use some global variable as static variable for all instance? and where i can initialize this global variable? –  Aug 28 '16 at 00:07
  • @user6751794 You should take a look at `initialization` and `finalization` sections at the bottom of units. That seems like the ideal thing in your case. – Jerry Dodge Aug 28 '16 at 02:02
  • plus1. I think a simple local (implementation) var will do it. – Gabriel Dec 16 '19 at 13:07
3

Expanding on Rudy's answer...

Delphi 5 did not yet have this available. But you could at least declare a global variable. I won't copy Rudy's code, but I will add that in order to initialize them (and clean them up if necessary), you should use the initialization (and finalization) sections of a unit. These go on the very bottom of a Delphi unit, like so...

unit Whatever;

...

interface

...

implementation

...

initialization
  MyGlobalVar := TMyGlobalVar.Create;
finalization
  FreeAndNil(MyGlobalVar);
end.

Or in your case...

initialization
  next_ID := 1;

And your scenario in particular won't require a finalization section.

Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327
-1

Sample of class variable declaration:

unit Unit2;

interface

type
  GlobalData = class
    class var V1: String;
    class var X1: Integer;
  end;

implementation

end.

usage sample from other unit:

procedure TForm1.FormCreate(Sender: TObject);
begin
  GlobalData.V1 := 'Yahoo';
end;

you don't need to create and destroy this class. it will be created automatically before everything else.

what is wrong in your sample: class variable must be declared inside class. i don't see class declaration in your sample. plus, as was mentioned before, Delphi 5 (very very old) do not support this feature.

Zam
  • 2,880
  • 1
  • 18
  • 33
  • 1
    @DavidHeffernan -- have you ever read till end. did you saw `Delphi 5 (very very old) do not support this feature. answered 12 hours ago` ? – Zam Aug 29 '16 at 05:42
  • Not much use then is it. And the penultimate paragraph is a little misleading. – David Heffernan Aug 29 '16 at 06:12