Returning arrays

Top  Previous  Next

What is translated > Types > Arrays > Returning arrays


In Delphi arrays can be returned from functions by value, but this is not allowed for C-style arrays  in C++. In C++ arrays are passed to functions by reference instead. That's what Delphi2Cpp*) does too. If TObjectArray is defined as:


type TObjectArray = array[1..3] of TObject;


or in C++:


typedef TObject* TObjectArray[3/*# range 1..3*/];



the following Delphi function:



function CreateArray: TObjectArray;


  Result[1] := TObject.Create;

  Result[2] := TObject.Create;

  Result[3] := TObject.Create;



becomes in C++ to:


TObjectArray& CreateArray(TObjectArray& result, uniquetype u)


  result[1 - 1] = new TObject();

  result[2 - 1] = new TObject();

  result[3 - 1] = new TObject();

  return result;



This function receives the array as reference parameter, so it can return the reference without danger, There is a second uniquetype parameter, which distinguishes the function from a possible overload:


procedure CreateArray(var arr: TObjectArray);

void CreateArray(TObjectArray& arr)



The function call:


procedure Test;


  arr2: TObjectArray;


  arr2 := CreateArray;



is translated by Delphi2Cpp to



void Test()


  TObjectArray arr2;

  CreateArray(arr2, uniquetype());




In this example the returned array reference isn't used at all. It is used however, if CreateArray delivers the value for another function:


procedure ProcessArray(arr: TObjectArray);



procedure Test2;





This becomes in C++:


void Test2()


  TObjectArray arrayreturn__0; ProcessArray(CreateArray(arrayreturn__0, uniquetype()));



At first Delphi2Cpp creates a local TObjectArray, which is passed to the CreateArray function and finally is directly passed as reference parameter to the other function. The treatment of array properties is similar.






*)  In contrast to Delphi2Cpp the old Delphi2Cpp in such cases created a helping array in the file scope which is used for an intermediate copy of the array


This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content