Object returned in method

In Delphi, if your function returns an object, the object is created for you (so you never have to do result := object.create;)

I think this is not the behavior in Oxygene (at least my nil address pointers would indicate this!)

Is there a reason for the difference? Is this intended behavior?

Delphi would never automatically instantiate the returned object. In any case, we would have to call the constructor of the returned object explicitly.

In the figure below, we can see from the disassembly window that the returned object was never automatically created by Delphi.

Note: without explicitly constructing the returned object, the implicit result will have undefined contents.

  • In that case, result points to random memory. As such, if you reference it, you would get an access violation.

Correct. Result, like all vars, is initialized fo zero memory; in case of a class type, that’s a nil pointer.

The “bad” thing of Delphi is, it doesn’t seem to automatically initialize Result to nil (i.e., set to default), but just leaving it undefined. Probably that made OP thought Delphi automatically did the construction when he saw result wasn’t nil.

I cannot believe I made a mistake (joke guys!) but I swear the last app I wrote that I had tested this but I must have been incredibly lucky instead! My bad!

If I ever reload Delphi on my computer I will go thru and fix any stupidities I have implemented thus way!

1 Like

Really? Ouch.