Recent

Author Topic: I guess I can't initialize variable at declaration of type object  (Read 2332 times)

Thaddy

  • Hero Member
  • *****
  • Posts: 16928
  • Ceterum censeo Trump esse delendam
Re: I guess I can't initialize variable at declaration of type object
« Reply #15 on: August 07, 2024, 03:48:17 pm »
I'll admit that I've never used legacy  objects, but record initialization syntax seems to work (at least in  {$mode objfpc}):

Code: Pascal  [Select][+][-]
  1. var
  2.   object_2: myObject = (myvariable := 10000);
This works, but there is a slight syntax error, the syntax is like this:
Code: Pascal  [Select][+][-]
  1. type    
  2.   TSomeObject = object
  3.     a,b:integer;
  4.   end;
  5.  
  6. var
  7.   S:TSomeObject = (a:100;b:200);
  8. begin
  9.   writeln(S.a, S.b:4);
  10. end.
Note that depending on application my previous slightly complex code can still be beneficial: e.g. if the object has a constructor you need to call it manually.
« Last Edit: August 07, 2024, 04:16:29 pm by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

jamie

  • Hero Member
  • *****
  • Posts: 6888
Re: I guess I can't initialize variable at declaration of type object
« Reply #16 on: August 07, 2024, 11:19:37 pm »
Yes it would be nice of the old objects would support operators because they can do inherited things where the records don't.

Consider this as an auto constructor and destructor where you can make auto created objects via records.

Code: Pascal  [Select][+][-]
  1.  
  2. unit Unit1;
  3. ...
  4.     M:TMemoryStream;
  5.   ..
  6.  
  7.   Dest.M := TMemoryStream.Create;
  8. ..
  9.  
  10. class operator myObject.Finalize(var Dest: myObject);
  11. begin
  12.   Dest.M.Free;
  13. end;
  14.  
  15. { TForm1 }
  16.  
  17.  
  18. end;
  19.  
  20. end.
  21.  
  22.  



Jamie, why did we need stream in your example? sorry for stupid questions

I didn't need the memory stream there, I just put it there as an example of how you can embed classes that need to be created and freed automatically.

Or even memory junks to something..

The only true wisdom is knowing you know nothing

Khrys

  • Full Member
  • ***
  • Posts: 226
Re: I guess I can't initialize variable at declaration of type object
« Reply #17 on: August 08, 2024, 07:27:33 am »
there is a slight syntax error
How did I miss that?  :o  I've used this correctly countless times before...  %)
Thanks for pointing it out  :-[

 

TinyPortal © 2005-2018