Search code examples
delphiexceptioninheritancepolymorphismdelphi-xe

VCL component causing error when try to free after have class changed


I have an application where I create a Popup menu class (lets say TNewPopupMenu) that inherited from TPopupMenu (that is created in the vcl)

On Create changing the class using

Procedure T.ChangeClass;
type
  PClass = ^TClass;

Begin
  PClass(FEventPopup)^ := TNewPopupMenu;
  TNewPopupMenu(FEventPopup).OnDismissed := CallbackDismissPopUpMenu;
End;

If I leave like this I get a error when the application closes and try to free FEventPopup, I try to do this so solve:

destructor T.Destroy;
type
  PClass = ^TClass;
begin
  TNewPopupMenu(FEventPopup).OnDismissed := nil;
  PClass(FEventPopup)^ := TPopupMenu;
  inherited;
end;

But I still getting an exception when the main form try to free FEventPopup, what else do I need to do?


Solution

  • The construction PClass(FEventPopup)^ := TNewPopupMenu; looks scary. It looks like you are tyring to change the class type at runtime and that is not possible.

    Whar are you trying to do?. If you want to create a class of type TNewPopupMenu, you can use:

    FEventPopup := TNewPopupMenu.Create(nil);
    

    Next define FEventPopup as a TNewPopupMenu. And preferably add an owner, so you don't have to worry about destruction. Don't forget to assign the popup menu to the appropriate controls.

    You won't need PClass(FEventPopup)^ := TPopupMenu;.

    If T is a TForm or a TForm descendant, you can create dynamical components in the OnCreate (and destroy them in the OnDestroy.

    And you better not use T as a classname. It gives you no clue on what it is doing.

    Besides, if you really want to use custom components, why not put it in a package and register it so you can use it in the form editor.