Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare an array object field in Delphi?

I tried do like this but got an error in constructor.

E2029 'OF' expected but '[' found

Dish = class
 public
    Dish_name: string;        
    Dish_id: integer;         
    Dish_number: integer;     
    Dish_units: string;        
    Dish_price: integer;      
    Dish_prime_cost: integer; 
    Dish_ingredients_id: array[1..100] of  Ingredients;

constructor Create( NewDish_name: string;
    NewDish_id: integer;  NewDish_number: integer;
    NewDish_units: string;  NewDish_price: integer;
    NewDish_prime_cost: integer;
    NewDish_ingredients_id:array[1..100] of  Ingredients);

  destructor Destroy;
end;

Ingredients it is class.

like image 929
T_E_M_A Avatar asked Jan 27 '26 05:01

T_E_M_A


1 Answers

You cannot declare a static array inline as a parameter. You need to declare a type:

type
  TIngredientsArray = array[1..100] of Ingredients;

And then use that type for both your field and your argument.

However, a statically sized array is probably not the best choice. What if you need more than 100 ingredients? What if you need only 1, but are forced to pass around 100? As your code stands, how can the dish class know how many ingredients have actually been provided?

Consider using a dynamic array instead.

You should also think about the lifetime and ownership of these ingredient objects. You pass the objects to the dish class. Does it assume ownership? That is, who is responsible for destroying all the ingredient objects? If you could use a value type for the ingredients, that is a record, then you might find that makes lifetime management simpler.

It is also idiomatic to use zero-based indexing for arrays in Delphi. Dynamic arrays are zero-based. Standard collection classes are zero-based. If you start using one-based arrays then experience says that you are going to store up confusion in the future.

like image 191
David Heffernan Avatar answered Jan 29 '26 19:01

David Heffernan