Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Instance without creating it

Tags:

delphi

I was wondering if it is possible to have an object instance without calling any constructor directly. Something like that:

var
  aObject : TMyObject;
begin
  aObject.MyMethod; //will cause an AV, but is it possible?
end;

Edit:

I know about static methods, but thats is not what i am looking for. I am looking for an way to get the constructor called without having to explicit call it.

like image 532
Rafael Colucci Avatar asked Mar 10 '26 03:03

Rafael Colucci


1 Answers

Delphi's objects are all heap-allocated: you can't simply declare an object and call methods on it, like you could do in C++ for example, you have to call an constructor to allocate and set up memory. But note even in C++ you are actually calling an constructor when you do that!

Maybe you can get away with a record and not an object? Example:

type
  TMyObject = record // name intentionally left as in OP's code
    procedure MyMethod;
  end;

procedure TMyObject.MyMethod;
begin
  // Do something
end;

// Use example:
procedure Test;
var MyObject: TMyObject; // TMyObject is a record so it is stack-allocated
begin
  MyObject.MyMethod; // Works.
end;
like image 169
Cosmin Prund Avatar answered Mar 12 '26 19:03

Cosmin Prund