views:

119

answers:

2

Say I have

type
  TLight = class
  private
    Ftimer : TTimer;
    property IsAutoRotating: Boolean read Ftimer.Enabled;

Obviously, this doesn't compile, but why not and how to solve this (preferably without keeping that state in a seperate var.

+3  A: 

The getter and setter of a property should be a method of the class or it's parent - or - a field of the class or it's parent.

Since FTimer.Enabled is neither the above construct won't work. You might create a getter function and setter procedure that will return this property of FTimer (getter) and set this property of FTimer (setter):

type:

property Enabled: Boolean read GetEnabled write SetEnabled;

now press CTRL-SHIFT-C for class completion. The 2 methods are now created for you.

In the getter type:

Result := FTimer.Enabled;

In the setter type:

FTimer.Enabled := Value;

Et voila!

.

Ritsaert Hornstra
+5  A: 

Your code won't compile because the property read and write specifiers must either refer to a field or method of the class. Ftimer.Enabled is neither of these.

To implement the IsAutoRotating property, you'll need to create a getter function:

type
  TLight = class
  private
    Ftimer : TTimer;
    function GetIsAutoRotating: Boolean;
  public
    property IsAutoRotating: Boolean read GetIsAutoRotating;
  end;

function TLight.GetIsAutoRotating : Boolean;
begin
  Result := Ftimer.Enabled;
end;
Phil Ross
And, you would probably want to move `property IsAutoRotating` to the `published` section of the class declaration.
PA
And protect against the AV generated if FTimer is not assigned.
skamradt
Why would you recommend publishing that property, PA? I see no evidence that the property would need to be accessed via its string name.
Rob Kennedy
@PA: There is absolutely no point having a published section on a class that is not derived from TPersistent or compiled with RTTI enabled.@skamradt: If it is a program error to reference this propery when fTimer is NIL then you should not "protect" against the AV. The AV tells you you have an error. In that case at most I would suggest an ASSERT() to test for a NIL fTimer, not protect against it. Only if IsAutoRotating has a valid meaning and value for a NIL fTimer case would I implement a conditional return in that case.
Deltics