[fpc-pascal] access violation?

Ryan Joseph ryan at thealchemistguild.com
Fri Jul 27 19:06:11 CEST 2018



> On Jul 27, 2018, at 10:16 AM, Dmitry Boyarintsev <skalogryz.lists at gmail.com> wrote:
> 
> type
>   TRobust = class(TObject)
>   public
>     v : Integer;
>     procedure RobustMethod;
>   end;
> 
> procedure TRobust.RobustMethod;
> begin
>   if Self = nil then Exit; // remove or comment out this line to start getting AVs
>   v := 5;
> end;
> 
> var
>   r : TRobust;
> begin
>   r := nil;
>   r.RobustMethod;
> end.
> 

I had no idea you could do that!

I’m totally confused now. Since when was it ok to call methods on nil objects? According to this test not only can you call methods on nil objects but it calls the method statically (like a class method), i.e the test prints “DoThis”. How is that possible?

type
	TMyClass = class
		procedure DoThis;
	end;

procedure TMyClass.DoThis;
begin
	writeln('DoThis');
end;

var
	obj: TMyClass;
begin
	obj := nil;
	obj.DoThis;


Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list