Why doesn't the Delphi compiler give a warning when a class method uses self?

At my workplace, we have code where the class function refers to Self , effectively creating a potential violation of access rights if the object is not initialized. Does the meaning of Self method of the class, how to refer to the class, and not to the object?

I assume that the only reason this works is because Self refers to a different class function , rather than a regular method.

I created the following test class:

 constructor TTest.Create; begin FTest := 'Hej'; end; procedure TTest.GoTest; begin ShowMessage(FTest); end; class procedure TTest.Test; begin Self.GoTest; end; 

However, when compiling, this causes an error:

 [dcc32 Error] Unit1.pas(51): E2076 This form of method call only allowed for class methods or constructor 

I also tested direct access to FTest, which gave another error:

 [dcc32 Error] Unit1.pas(51): E2124 Instance member 'FTest' inaccessible here 

But I wonder, however, whether it is possible to have a case where Self potentially dangerous in class methods.

I know that referring to global objects and I assume that they are always there.

+4
source share
1 answer

Is the value of Self a change in the class method to refer to the class, not the object?

In a class method, Self refers to the class. The documentation says:

In the defining declaration of a class method, the Self identifier represents the class in which the method is called (which may be a descendant of the class in which it is defined.) If the method is called in the class C, then Self is of type C. Thus, you cannot use Self to access to instance fields, instance properties, and ordinary (object) methods. You can use Self to call constructors and other methods of the class, or to access class properties and class fields.

The class method can be called through a link to a class or a link to an object. When it is called through an object reference, the object's class becomes the value Self.

The compiler will not mind you using Self , as this is a legitimate and supported thing. It just complains when you try to use instance instances, instance methods, etc.

Self has this meaning in class methods for the same reason as in instance methods. It allows you to fully specify the character and, thus, avoid the ambiguity of the review. What else allows you to access the actual class on which the method is being called. This may be a descendant of the class in which the method is defined.

It is interesting, however, whether it is possible to have a case where Self potentially dangerous in class methods.

I do not see any particular danger inherent in this part of the language. In fact, using Self reduces the volume and, therefore, reduces the risk of inadvertently accessing a local variable rather than a member of a class.

+6
source

All Articles