In Delphi does casting an object to its parent take a lot more memory?

Viewed 212

I'm using a TMemoryStream and I need to pass it to var TStream procedure (external lib). I just cast my TMemoryStream to TStream like this:

var
    myStream: TMemoryStream;

begin
    //...
    ExternalProcedure(TStream(myStream)); //procedure ExternalProcedure(var AStream: TStream);
end;

Is this something to avoid? Does it take a lot of extra memory (the stream in question can be several MB)? My guess is no, but not 100% sure in Delphi.

2 Answers

MBo is right: this kind of cast will only instruct the compiler to assume that the type is the one you specify. This is essentially a cast that will make no additional code being generated. (But there are many exceptions when you cast value types.)

However, I generally would avoid this kind of unsafe cast. Here is an example of what can go wrong:

type
  TAnimal = class
    DNASequence: string;
  end;

  TSpider = class(TAnimal)
    MoultCount: Integer;
  end;

procedure ChangeAnimal(var AAnimal: TAnimal);
begin
  FreeAndNil(AAnimal);
  AAnimal := TAnimal.Create;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  Spider: TSpider;
begin
  Spider := TSpider.Create;
  try
    Spider.DNASequence := 'CTGA...';
    Spider.MoultCount := 3;
    ChangeAnimal(TAnimal(Spider));
    ShowMessage(Spider.MoultCount.ToString); // Oops! The `TSpider` variable
                                             // points to a `TAnimal` object!
  finally
    Spider.Free;
  end;
end;

Casting does not create new objects and correpondingly does not get new memory. It is just instruction for compiler to provide type compatibility

Related