Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new Pointer to Class

I want to create a Pointer to a Class named "CustomParam", so I declared

pCustomParam = ^CustomParam

The Class CustomParam got following class variables, which should be set to 0 in constructor:

var keyArray: array of String;
var valueArray: array of String;
var paramArray: array of pCustomParam;
var isParamArray: array of Boolean;
var size: Integer;   

The Constructor looks like that:

constructor CustomParam.create;
begin
    inherited; 
    size:= 0;
    SetLength(keyArray,0);
    SetLength(valueArray,0);
    SetLength(isParamArray,0);
    SetLength(paramArray,0); 
end;

and was declared like that:

constructor create; overload; 

Now I try to create the Pointer to CustomParam with "new" like following:

var pointerToCustomParam: pCustomParam; 
begin
new(pointerToCustomParam);

But it don't jump to constructor of CustomParam Class. If I call the constructor manually like following:

pointerToCustomParam^.create; 

The application will crash on SetLength commands.

What I noticed is, that the variable "pointerToCustomParam" got rubbish content direct after the "new" function.

I hope you are able to help me and the information are enough :)

Thank you :)

like image 250
Daniel Müller Avatar asked Apr 29 '26 00:04

Daniel Müller


1 Answers

The proper way to create an instance of a type is to call the constructor on the type and assign the result to a variable of that type:

var
  Param: CustomParam;

Param := CustomParam.Create;

Instances created that way are already references, so there's rarely a need for an additional pointer.

If you really must have a pointer, then start by declaring the type:

type
  PCustomParam = ^CustomParam;

Then declare a variable:

var
  Param: PCustomParam;

Allocate memory for the contents of the thing it points to:

New(Param);

That doesn't necessarily assign a valid value to the CustomParam reference it points to, but if it does, is assigns the value nil. So finally, assign a value to that newly allocated memory:

Param^ := CustomParam.Create;

Notice how we still have to call the constructor, and we never call the constructor on the object we're creating, because that object doesn't exist until after the constructor is called.

like image 63
Rob Kennedy Avatar answered Apr 30 '26 13:04

Rob Kennedy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!