Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor without an override directive

Tags:

oop

delphi

What is wrong with this code:

type
    TobjAvisos = class

        public
            constructor Create;
            destructor Free;


    end;

implementation


constructor TobjAvisos.Create;
Begin
    inherited Create;

end;

destructor TobjAvisos.Free;
begin
    inherited Destroy;

end;

It compiles with no warnings but FixInsight returns a Warning: "W522 Destructor without an override directive"

like image 839
Jlouro Avatar asked May 28 '15 19:05

Jlouro


1 Answers

The problem is that you are expected to override the virtual destructor Destroy. That virtual destructor is what is called by the non-virtual method Free.

As it stands, the only way to destroy your class is to call the destructor directly. But Delphi classes are expected to support being destroyed by way of the Free method.

Your class should be like this:

type
  TobjAvisos = class
  public
    constructor Create;
    destructor Destroy; override;
  end;

Overriding the virtual destructor Destroy is the only way to make your class work correctly with the Free method.

Now, there are two main reasons for using the virtual destructor Destroy and supporting Free:

  1. Free can safely be called on a nil object reference. A destructor cannot. This is essential for the object construction mechanism for exception handling.
  2. Supporting Free allows the object to be safely destroyed even if the run time type of the object is more derived than the compile time type of the object reference.

Some useful reading on related topics can be found here: Why should I not use "if Assigned()" before using or freeing things?

like image 119
David Heffernan Avatar answered Sep 28 '22 03:09

David Heffernan