Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - why does this function work if the class is not created?

Consider this class:

unit Unit2;

interface

type

  TTeste = class
  private
    texto: string;
  public
    function soma(a, b: integer): string;
  end;

implementation

procedure TForm2.Button1Click(Sender: TObject);
var
  teste: TTeste;
begin
  teste:= nil;
  teste.texto:= '';//access violation
  showmessage(teste.soma(5, 3));//no access violation
end;

{ TTeste }

function TTeste.soma(a, b: integer): string;
begin
  result:= (a+b).ToString;
end;

end.

should it really work? why? the var crashed but the function doesnt, does it works like a class funtion?

like image 991
Henrique Faria Avatar asked Jun 14 '18 22:06

Henrique Faria


People also ask

What is the relationship between object and class in Delphi?

The relationship between object and class is the same as the one between variable and type. As in most other modern OOP languages (including Java and C#), in Delphi a class-type variable doesn't provide the storage for the object, but is only a pointer or reference to the object in memory.

What is the difference between method and class in Delphi?

He is also proficient in XML, DHTML, and JavaScript. In Delphi, a method is a procedure or function that performs an operation on an object. A class method is a method that operates on a class reference instead of an object reference.

What is the use of Create constructor in Delphi?

The Create constructor is a class method, as opposed to virtually all other methods you'll encounter in Delphi programming, which are object methods. A class method is a method of the class, and appropriately enough, an object method is a method that can be called by an instance of the class.

How do you declare an object type in Delphi?

The Delphi compiler allows an alternative syntax to class types. You can declare object types using the syntax: type objectTypeName = object ( ancestorObjectType ) memberList end; where objectTypeName is any valid identifier, ( ancestorObjectType) is optional, and memberList declares fields, methods, and properties.


1 Answers

This works because you are not attempting to access any fields of the class. The function doesn't require any memory allocation. If the field texto was used in that function, then it would crash (as you see in your other test), because that memory isn't addressed. But here, there is no memory involved. Both a and b (and the function result for that matter) are allocated elsewhere outside of the class. Part of the instantiation process is allocating memory for each and every one of the fields in the object.

This is just coincidental. It's still highly discouraged to actually use something like this. If you feel the need to access the function without instantiation, then you should make it a class function instead.

like image 91
Jerry Dodge Avatar answered Nov 02 '22 23:11

Jerry Dodge