Instance Reference in Delphi?

What is the equivalent of Delphi 'this' in C ++? Could you give some examples of its use?

+6
source share
2 answers

In most cases, you should not use self in methods.

In fact, this is similar to having an implicit self. prefix self. when accessing class properties and methods in a class method:

 type TMyClass = class public Value: string; procedure MyMethod; procedure AddToList(List: TStrings); end; procedure TMyClass.MyMethod; begin Value := 'abc'; assert(self.Value='abc'); // same as assert(Value=10) end; 

self should be used when you want to point the current object to another method or object.

For instance:

 procedure TMyClass.AddToList(List: TStrings); var i: integer; begin List.AddObject(Value,self); // check that the List[] only was populated via this method and this object for i := 0 to List.Count-1 do begin assert(List[i]=Value); assert(List.Objects[i]=self); end; end; 

this code above will add an item to the TStrings list, and List.Objects [] points to an instance of TMyClass. And he will verify that this applies to all elements of the list.

+3
source

In delphi, Self is the equivalent of this. It can also be assigned as described here .

+9
source

Source: https://habr.com/ru/post/893380/


All Articles