Home > database >  How to use predefined variables in a class declaration
How to use predefined variables in a class declaration

Time:11-23

Is there a way to use a predefined variable inside a class or define it with a start value? My code:

TRoom = class(TObject)
   private
    pos: array[0..2] of integer;
    up: TRoom;
    right: TRoom;
    down: TRoom;
    left: TRoom;
--> freeSlots: array[0..3] of string = ('up','right','down','left'); <--
    content: string;
   end;

CodePudding user response:

Is there a way to use a predefined variable inside a class or define it with a start value?

No, you cannot declare initial values for instance member fields of a class. Classes are default intialized (i.e. to zero). If you want to assign an initial value then you should do so in a constructor.

CodePudding user response:

It's possible to declare a constant field with a predifined value. If you later want to change the value, there is a trick. Using the compiler option "Writable const {$J }" it is possible to alter the value.

TRoom = class(TObject)
   private
      pos: array[0..2] of integer;
      up: TRoom;
      right: TRoom;
      down: TRoom;
      left: TRoom;
      content: string;
    const
      {$J } //Enable writable constants
      freeSlot: array[0..3] of string = ('up','right','down','left');
      {$J-} //Disable writable constants
   end;

var
  TR : TRoom;
begin
  TR := TRoom.Create;
  try
    for var i := Low(TR.freeSlot) to High(TR.freeSlot) do
      WriteLn(TR.freeSlot[i]);

    TR.freeSlot[0] := 'Hello';

    for var i := Low(TR.freeSlot) to High(TR.freeSlot) do
      WriteLn(TR.freeSlot[i]);

  finally
    TR.Free;
  end; 
end;

Note: As @Andreas points out, the change of a the writable const will affect all instantiated classes of TRoom, which may limit the use of this trick.

  • Related