The code works, but is technically dubious, indeed, the class field reordering can give you wrong access pointers. If you want to prevent this you can turn that off:
{$optimization orderfields-}
If you need to access strict private or private fields like you do above, the code is not good in the first place.
It counts towards implementation detail, so is not future proof as well.
A better, safer way is to use a proxy class definition with higher visibilities. (a.k.a. a class cracker)
{$mode objfpc}{$H+}
type
TTest = record
Valore: integer;
end;
PTest = ^TTest;
TClasseTest = class
private
FTest: TTest;
public
property Test: TTest read FTest write FTest;
end;
TTestCracker = class
public
FTest: TTest;
property Test: TTest read FTest write FTest;
end;
var
ClasseTest: TClasseTest;
begin
ClasseTest := TClasseTest.Create;
TTestCracker(ClasseTest).FTest.Valore:=20; //direct field access
WriteLn(ClasseTest.Test.Valore);
ClasseTest.Free;
Readln;
end.
This will also work when reorderfields is on. (reordering would be the same)
If that solution is any good? Basically same answer: if you need to access private class fields your code is wrong.
But a class cracker is a cleaner solution.
If it was just the property access, the solution is much simpler:
var
ClasseTest: TClasseTest;
T:TTest;
begin
ClasseTest := TClasseTest.Create;
T.Valore := 40;
ClasseTest.Test:=T;
WriteLn(ClasseTest.Test.Valore);
ClasseTest.Free;
Readln;
end.
Use the proper type to write to the property, so use a TTest.
You can not write to the property field value directly, you must use a TTest variable because that is what you defined....