tags:

views:

226

answers:

2
uses Classes, SysUtils;

type
  TMyObject = class (TObject)
  private
    Fsl: TStringList;
  public
    constructor Create;
    destructor Destroy; override;
  end;

implementation

constructor TMyObject.Create;
begin
  Fsl := TStringList.Create;
end;

destructor TMyObject.Destroy;
begin
  FreeAndNil (Fsl);
  inherited;
end;

I get an access violation when the TStringList is created in the constructor.

This only happens if Fsl is declared as a field of TMyObject. If it is for example a global var, everything works as usual.

What am I doing wrong?

+5  A: 

How do you create TMyObject?

It looks like the Access violation is because of the object self is not created.

So you should use:

myobject : TMyObject;
begin
  myobject := TMyObject.Create;

  // ...
end;
Gamecat
Stupid me! You're right, I had a "MyObject.Create" instead of "MyObject := TMyObject.Create"So obvious that I didn't see it...Thanks a lot for the hint!
Holgerwa
No problem we all have our "blonde" moments ;-).
Gamecat
A: 

You have forgotten to call inherited in the constructor of your object (like you have called in destructor).

constructor TMyObject.Create;
begin
  inherited;
  Fsl := TStringList.Create;
end;

···························
Neftalí -Germán Estévez-

Neftalí
There is absolutely no point in calling inherited in the constructor of a type which derives directly from TObject. The call does nothing.
Mihai Limbășan
Yes....and then sometime later you'll change the ancestor class to something other than TObject and have all kinds of nasty problems it'll take time to find. Best ALWAYS to call the inherited constructor as a defensive practicsc.
Jim
If you later change the ancestor class to something else you will have to review this type's implementation too, otherwise you're simply irresponsible... I prefer the lazy approach - don't add to the runtime until it's needed :)
Mihai Limbășan
-1 because the answer's irrelevant and actually incorrect. Create doesn't assign Self, so calling inherited or not won't solve the problem. Gamecat hit the nail on the head: Self = nil because the OP used MyObject.Create not TMyObject.Create.
Frank Shearar