[fpc-pascal] Records as properties and Delphi compiler error

Martin Friebe fpc at mfriebe.de
Mon Jun 8 20:33:48 CEST 2009


fpclist at silvermono.co.za wrote:
> On Sunday 07 June 2009 22:19:47 Jonas Maebe wrote:
>   
>> On 07 Jun 2009, at 10:35, fpclist at silvermono.co.za wrote:
>>     
>>> A high level, a class is like a record that has been modified to
>>> include
>>> functions and procedures. I know that I'm over simplifying thing
>>> here, please
>>> bare with me.
>>>       
>> The difference you skip over is the fundamental reason why one works
>> and the other doesn't: a class is a pointer, while a record is a value.
>>     
>
> I understand the difference, but a pointer to a record still suffers the from 
> the same problem as a pointer to a class i.e. if memory is not allocated then 
> the code fails at runtime. It's interesting to note though, that Delphi allows 
> the assignment to the fields of a record type property via the with - do 
> construct. Is this also the case with FPC 2.3.1?
>   
  property ARecord: TSomeRecorType read FTheRecord;
  property AClass: TSomeClassType read FTheClass;

must be treated the same as
  function GetARecord: TSomeRecorType;
  function GetAClass: TSomeClassType;

Why? Because that is what a property is for. A property means you are 
free to change the "read" part to use a getter-function. And doing that 
change *must* not break any code.

You can not (not in a sensible way) do
  GetARecord() := ....
Neither does it make sense to do
  GetARecord().X := ....

The last bit may be possible, but it would assign .X to a *temporary* 
copy of the record, same as
  MyTemp := GetARecord();
  MyTemp.X := ....

What is the Point of this assignment, the value is lost, and unless you 
actually have a temp variable (like in the expanded example) you can not 
even retrieve the assigned value.

However
  with GetARecord() do begin
      x := 5;  // only the temp copy
     writeln(x); // using the value from the temp copy
  end;

-------------
As for classes
   GetAClass()
does not return a temporary copy of your class, it return a temporary 
pointer to your class.

so the following makes NO sense
   GetAClass() := TClass.Create; // trying to replace the class

but
   GetAClass().X := 5;
following the temporary pointer still leads to the real object

-------------
This is because TClass behaves like a pointer.
Record does not behave like a pointer ** (the whole memory occupied by 
all values of the record is copied). **

This difference also applies if you pass such values as params to a 
procedure or function.


Martin









More information about the fpc-pascal mailing list