I ask you to promote your understanding of I.
Please note the following:
type PTestObject = ^TTestObject; TTestObject = class(TObject) private FCaption : String; public procedure MakeThePointer; property Caption : String read FCaption write FCaption; end; TForm4 = class(TForm) ButtonFirst: TButton; ButtonSecond: TButton; ButtonThird: TButton; procedure ButtonFirstClick(Sender: TObject); procedure ButtonSecondClick(Sender: TObject); procedure ButtonThirdClick(Sender: TObject); private public end; var Form4: TForm4; PointerOfTest : PTestObject; TestObj : TTestObject; implementation {$R *.dfm} procedure TTestObject.MakeThePointer; begin PointerOfTest := @Self; end; procedure TForm4.ButtonFirstClick(Sender: TObject); begin TestObj := TTestObject.Create; TestObj.Caption := 'Hello'; TestObj.MakeThePointer; end; procedure TForm4.ButtonSecondClick(Sender: TObject); begin TestObj.MakeThePointer; ShowMessage(PointerOfTest^.Caption); end; procedure TForm4.ButtonThirdClick(Sender: TObject); begin // TestObj.MakeThePointer; - Because I do not do this I get Access Violation ShowMessage(PointerOfTest^.Caption); end;
The idea is to create a pointer to TestObj Self , and then access it again later. If I call MakeThePointer on the same Click event ( ButtonSecondClick ), where I access this pointer, it works fine. If I do not call MakeThePointer before accessing the pointer ( ButtonThirdClick ), it seems that TestObj Self does not exist in such a way that the previously created pointer is valid, and I get an access violation.
Please correct me if I am wrong, but I assume that Self is a variable local to each of the methods of the object. So it will only have scope for each of these methods separately?
Now consider this ... If so, why does the next work when I click ButtonFirst and then ButtonSecond? It seems that the Self variable has landed at the same address, which allows us to work as follows. Can I assume that the Self variable will always be at the same address or will it change?
type TFormOther = class(TForm) ButtonFirst: TButton; ButtonSecond: TButton; procedure ButtonFirstClick(Sender: TObject); procedure ButtonSecondClick(Sender: TObject); private public procedure MakeThePointer; procedure SetTheCaption; end; var FormOther: TFormOther; PointerOfForm : ^TForm; implementation {$R *.dfm} procedure TFormOther.MakeThePointer; begin PointerOfForm := @Self; end; procedure TFormOther.SetTheCaption; begin PointerOfForm^.Caption := 'Hello'; end; procedure TFormOther.ButtonFirstClick(Sender: TObject); begin MakeThePointer; end; procedure TFormOther.ButtonSecondClick(Sender: TObject); begin SetTheCaption; end;
source share