Can I create an object of the same type as myself?

I have my own class, let's call it TMyObject, which should return a slightly modified copy of itself. So, one of its functions should return an object of the same type as itself:

function TMyObject.TrimEnds: TMyObject;
begin
  Result:= TMyObject.Create;
  Result.DoStuff;
edn;

Can I do it? Is it legal what I do?

I mean, I already tried this, and the compiler allows me to do this, but I wonder if there will be long-lasting / hidden negative effects.

Any thoughts would be appreciated. Thank you


Edit: A new slightly modified copy will be saved to disk. This is a kind of "Save As ...". How it works: the original object creates a copy of itself, instructs this copy to make some changes and save to disk. Then the original releases a copy. This way I keep the original object in memory unchanged, but I have a modified version of this on disk.

You may think that my object is holding an image. I need a function that returns a slightly modified copy of the image.

+5
source share
5 answers

but I am wondering if there will be long time / hidden negative effects.

, . , , .

+5

, , . , . .

, , ( ), .

, " " . ...

+2

, , .

1: .

class function TMyObject.CreateSpecialized: TMyObject;
begin
  Result := TMyObject.Create;
  //initialize Result
end;

anObj := TMyObject.CreateSpecialized;

2: . .

constructor TMyObject.CreateSpecialized;
begin 
  Create; // make sure everything is initialized correctly
  // now do custom initialization
end;

anObj := TMyObject.CreateSpecialized;

, .

, .

constructor TMyObject.CreateSpecialized(obj: TMyObject);
begin
  Create;
  intField := obj.IntField * 2;
end;

anObj := TMyObject.CreateSpecialized(otherObj);
+2

, TMyObject, TMyOtherObject = class(TMyObject), TrimEnds TMyObject TMyOtherObject, .

, :

TMyObjectClass = class of TMyObject;

function TMyObject.TrimEnds: TMyObject;
begin
  Result:= TMyObjectClass(ClassType).Create;
  Result.DoStuff;
end;
+2

, . , , .

+1
source

All Articles