Ivor
Ivor

Reputation: 21

Invalid Pointer Operation freeing an object

Being new to OOP, I'm curious why Delphi XE7 generated an invalid pointer operation on a logging class I was using whenI try to free it. So I created a simple test to create an object and then free it. I'm not sure what I'm missing here and why it throws this exception when MyObject.Free is called.

In the first unit, I create an instance of this object as shown here.

unit Unit1;
interface
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Unit2;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  MyObject: TMyObject;

implementation
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  MyObject := TMyObject.Create;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  MyObject.Free;
end;

end.

In the 2nd unit, I have the object defined as follows.

unit Unit2;
interface
uses System.Classes;

  type
  TMyObject = class
  public
    constructor Create;
    destructor Free;
  end;

implementation

constructor TMyObject.Create;
begin
  inherited Create;
end;

destructor TMyObject.Free;
begin
  inherited Free;
end;

end.

Any help is appreciated.

Upvotes: 2

Views: 1213

Answers (1)

David Heffernan
David Heffernan

Reputation: 613442

Always implement a destructor by overriding the virtual destructor named Destroy.

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

constructor TMyObject.Create;
begin
  inherited;
end;

destructor TMyObject.Destroy;
begin
  inherited;
end;

To destroy an instance call the method named Free in TObject. This calls the virtual destructor Destroy only if the instance is not nil.

Learn more from the documentation:

The name MyObject is weak. Object is used for instances. Class is used for classes.

Upvotes: 5

Related Questions