Search code examples
delphidelphi-7

Creating a form that has not been declared works - I don't know why


I'm using Delphi 7 (I know it's antique) and am a bit confused by a form I'm creating as needed and destroying when done with it.

From my main form I create another form requesting a Username and Password. The newly created form properties etc are contained in a another unit and is included in the Uses clause.

In my main form I previously "had" the following code;

var
  MyOtherForm: TMyotherform;
Begin
  MyOtherForm := TMyotherform.create(Nil);

    { Then I do stuff - blah blah }

  MyOtherForm.free;
End;

My question is, when I remove the declaration for MyOtherForm in my main unit it still works without error. For example;

{ var // removed
   MyOtherForm: TMyotherform; // removed }

Begin
  MyOtherForm := TMyotherform.create(Nil);

    { Then I do stuff }

  MyOtherForm.free;
End;

The same result, the form is created as usual and destroyed. What I cannot understand is why. Have I been doing it wrong in the past by declaring my form in the main unit, or does having it declared in a separate unit sufficient?


Solution

  • By default, Delphi creates a global variable for the form. It is added just below the class declaration of the form.

    The name for that variable is the class name minus the 'T', so it's the same name you used for your local variable, which is why the code still works: you just stored a new reference in that global variable.

    If you have an auto-create form, Delphi will create an instance of the form on start-up of the application, and store the reference in that global. You can manage auto-created forms and data modules in the project options, or you can simply edit the dpr file, in which you will find a line like:

    Application.CreateForm(TMyotherform, Myotherform);
    

    But even if your form is not auto-created, Delphi still adds that global variable.

    Personally, I don't like those global variables at all, and I always remove them manually when I create a form or a data module. Unfortunately, there doesn't seem to be a possibility to configure this.

    So: Remove the global and declare the local variable like you did in your original code. That is the right way to do it. The global is there to make it easier for beginners, but it's not helping the maintainability of your application.