Henrique Faria
Henrique Faria

Reputation: 69

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?

Upvotes: 6

Views: 633

Answers (1)

Jerry Dodge
Jerry Dodge

Reputation: 27266

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.

Upvotes: 13

Related Questions