0

Delphi 2010. I am trying to initialize class variables in the constructor of a class (A). Then I want to have a reference to that class throughout the functions of another class (B - the main Form). When I try to initialize the class using a local variable in a B function, all works but if I declare an instance of A in B's private or public areas or under var, it throws an eaccessviolation when Create is called. Having a ref to A global to B is absolutely essential in many programming tasks. Just cannot find a way to do it.

My code:

uses MyFavs;

type
  TForm4 = class(TForm)
    procedure FormActivate(Sender: TObject);
  private

  public
    mfav : TMyFavs;
  end;

var
  Form4: TForm4;

implementation

{$R *.dfm}

procedure TForm4.FormActivate(Sender: TObject);
begin
    mfav.Create;   //crash here
end;

TMyFavs is just dummy code that declares a private integer and assigns it value 1 in the constructor. Even if the constructor does nothing or there is no declared constructor, calling Create still throws the exception. The problem is not there, it must be in the declaration of myfav global to the class Form4 and this happens whether I put the declaration under the type's private, public or var. I know this is very basic but I cannot find the answer.

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
Andy
  • 21
  • 1
  • 1
    mFav := TMyFavs.Create`. – Ken White Aug 25 '19 at 00:01
  • @Ken How did you single-handedly mark it as a duplicate of 4 different questions? I didn't even know you could do that. – Jerry Dodge Aug 25 '19 at 00:40
  • You need to explicitly `assign` the variable by calling its `constructor`, which is usually `Create`. `mFav` is a variable, which is meant to reference an instance of this class. `TMyFavs` is a class *type*, defining the structure. Initially, `mFav` is `nil`, meaning no instance is assigned to it yet. When you call `Create`, it attempts to access an instance, but since there's none there, you get an Access Violation. You need to *assign* a new instance by explicitly using the class name, `TMyFavs`. So as others have said, `mFav := TMyFavs.Create;` – Jerry Dodge Aug 25 '19 at 00:57
  • @JerryDodge: Gold badge privilege. I closed it as a duplicate of a single post, and then added the other links. – Ken White Aug 25 '19 at 01:03
  • @JerryDodge: FYI https://meta.stackexchange.com/q/230865/172661 – Ken White Aug 25 '19 at 02:51
  • @KenWhite I have gold badges and didn't know adding multiple duplicate links was possible – Remy Lebeau Aug 25 '19 at 19:34
  • @RemyLebeau: If you use the dupe hammer to close a post, there's an edit link available to you (in the lower right corner of the area with the link to the dupe). Clicking that link lets you add additional duplicate links. – Ken White Aug 25 '19 at 22:55
  • @KenWhite cool thanks – Remy Lebeau Aug 26 '19 at 01:46

0 Answers0