Recent

Author Topic: record operator initialize in a class, when does it get called?  (Read 1219 times)

jamie

  • Hero Member
  • *****
  • Posts: 6550
Lets say we have this
Code: Pascal  [Select][+][-]
  1. Type
  2. TMyRecord = Record
  3.  X,Y:Integer;
  4. Class Operator initialize(var O:TmyRecord);
  5. end;
  6.  

And I put it in a class, lets say in the public area of TFORM1.

Code: Pascal  [Select][+][-]
  1. Tform1 = Class(...)
  2.  
  3. Public
  4.    Myrecord:TMyRecord;
  5. End;
  6.  
  7.  

While I am in the constructor of Form1, I can see that MYRecord has gotten initiaiized.

Where at what point during the creation of TFORM1 or any class that houses records like this, does the Initialize code get called ?
The only true wisdom is knowing you know nothing

Khrys

  • Jr. Member
  • **
  • Posts: 90
Re: record operator initialize in a class, when does it get called?
« Reply #1 on: August 09, 2024, 07:32:14 am »
As a stack trace:

Code: Pascal  [Select][+][-]
  1. #0  class operator TMyRecord.Initialize(var O: TMyRecord);
  2. #1  class function TObject.InitInstance(Instance: Pointer): TObject;
  3. #2  class function TObject.NewInstance(): TObject;
  4. #3  constructor TForm1.Create();

In other words, it's done right after the instance's memory is allocated (and zeroed) in the preamble of the constructor. If you take a look at the source of  TObject.InitInstance  you'll see comments and some code related to management operators.

jamie

  • Hero Member
  • *****
  • Posts: 6550
Re: record operator initialize in a class, when does it get called?
« Reply #2 on: August 09, 2024, 11:12:55 pm »
Thank you for that information, that is exactly what I was looking for.

I don't recall seeing that in the DOCs?
The only true wisdom is knowing you know nothing

Thaddy

  • Hero Member
  • *****
  • Posts: 15639
  • Censorship about opinions does not belong here.
Re: record operator initialize in a class, when does it get called?
« Reply #3 on: August 10, 2024, 05:56:22 pm »
Well, https://www.freepascal.org/docs-html/3.2.2/rtl/system/tobject.newinstance.html.
Anything after that gets called later.
( The doc is not totally correct: overriding NewInstance allows for allocating a class on the stack too. Only use if you know what you are doing. )
« Last Edit: August 10, 2024, 06:00:12 pm by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

PascalDragon

  • Hero Member
  • *****
  • Posts: 5672
  • Compiler Developer
Re: record operator initialize in a class, when does it get called?
« Reply #4 on: August 11, 2024, 08:29:25 pm »
I don't recall seeing that in the DOCs?

Well, it should probably be mentioned here... Best file a bug report against the documentation then.

 

TinyPortal © 2005-2018