8
votes

I have a very basic and simple class like this:

unit Loader;

interface

uses
  Vcl.Dialogs;

type
  TLoader = Class(TObject)
  published
      constructor Create();
  end;

implementation

{ TLoader }    
constructor TLoader.Create;
begin
   ShowMessage('ok');

end;

end.

And from Form1 i call it like this:

procedure TForm1.Button1Click(Sender: TObject);
var
 the : TLoader;
begin
  the := the.Create;
end;

Now, just after the the := the.Create part, delphi shows the message with 'ok' and then gives me an error and says Project Project1.exe raised exception class $C0000005 with message 'access violation at 0x0040559d: read of address 0xffffffe4'.

Also it shows this line:

constructor TLoader.Create;
begin
   ShowMessage('ok');

end; // <-------- THIS LINE IS MARKED AFTER THE ERROR.

I am new at delphi. I am using Delphi XE2 and i couldnt manage to fix this error. Does anyone show me a path or have solution for this?

2
I don't know what var instance: TLoader is supposed to do. Are you sure you need that global variable? It seems like you intend to declare local TLoader variables instead.Andreas Rejbrand
The question is not "How can i declare a class". Its an exception that throwed by Delphi and i couldn't realized that it was from wrong declaration. :)xangr
@xangr My comment was not really aimed at you. This is an obvious duplicate. I'm sure I've answered it more than once. I'm sure both Andreas and Mason have too. But I couldn't quickly find a question to illustrate that. Stack Overflow search doesn't really work very well, but I suspect that it is a really hard problem.David Heffernan
It's hard to find duplicates of this question, @David, because it's hard to ask this question generically. We've seen many instances of the underlying problem, but each time, it's presented as a "debug my code" question because that's the only way to phrase the question from the point of view of someone who doesn't already know what's wrong.Rob Kennedy
Xangr, didn't the compiler warn you that you were using an uninitialized variable?Rob Kennedy

2 Answers

18
votes
var
  the : TLoader;
begin
  the := the.Create;

is incorrect. It should be

var
  the : TLoader;
begin
  the := TLoader.Create;
6
votes

You've got the syntax wrong. If you're constructing a new object, you should use the class name, not the variable name, in the constructor call:

procedure TForm1.Button1Click(Sender: TObject);
var
 the : TLoader;
begin
  the := TLoader.Create;
end;