comp.lang.ada
 help / color / mirror / Atom feed
From: Adam Beneschan <adambeneschan@aol.com>
Subject: Re: How can I declare a collection of an interface?
Date: Fri, 2 Aug 2013 11:28:30 -0700 (PDT)
Date: 2013-08-02T11:28:30-07:00	[thread overview]
Message-ID: <2f3480f0-644a-427b-b781-7f20cf6de9d6@googlegroups.com> (raw)
In-Reply-To: <e520357f-db43-4f61-a850-ee622aaf66f4@googlegroups.com>

On Friday, August 2, 2013 9:39:14 AM UTC-7, Graham Stark wrote:
> Hi,
> 
>    if I have (say):
> 
> type Person is interface;
> 
> and I want to declare a collection of Person, how can I declare the type I'd need? I've tried:
> 
> type PA is array(1..2) of Person;

Assuming you want the array elements to be possibly different types that are derived from Person, you'll need to declare an access type:

  type Person_Acc is access all Person'Class;
  type PA is array(1..2) of Person_Acc;

Since an object of type Person'Class could be lots of other types, possibly of different sizes, Ada can't create an array of Person'Class.  Arrays are only useful when all the elements are the same type.  That's why you have to use an access type.  If you're coming from another language such as Java or C#, those languages will automatically give you a pointer if you declare an array of some class type.  Ada doesn't.  You have to tell it you want an access type (i.e. pointer).  'Class means "an object of this type or some type derived from it"; this is something else that Java/C# give you automatically, but in Ada you have to be explicit about this because sometimes you don't want that automatically.

> or
> 
> package PV is new Ada.Containers.Vectors( Positive, Person );
>  
> and the same with 'Class.

You could use Person_Acc in the same way:

  package PV is new Ada.Containers.Vectors (Positive, Person_Acc);

However, the Ada.Containers packages are able to handle "indefinite types" themselves, and they should take care of the pointer stuff for you.  To do this, you have to use Indefinite_Vectors instead of Vectors:

  package PV is new Ada.Containers.Indefinite_Vectors (Positive, Person'Class);

Person'Class is an "indefinite" type because we don't know beforehand what the actual type of the object will be.

                              -- Adam

  parent reply	other threads:[~2013-08-02 18:28 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2013-08-02 16:39 How can I declare a collection of an interface? Graham Stark
2013-08-02 16:53 ` Eryndlia Mavourneen
2013-08-02 18:28 ` Adam Beneschan [this message]
2013-08-03  8:04   ` Graham Stark
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox