Section 12.1 - Declaring Access Types

It is often very useful to have a variable that, instead of storing a value, stores a reference to some other object. Such variables are called access variables in Ada, and are essentially equivalent to pointers or references in other languages. One common use of access variables is to implement items of varying size.

To create such variables, first create a type for it; these types are called access types. Here's an example of an access type declaration, declaring that variables of type Node_Access can access (reference) objects of type Node:

  type Node_Access is access Node;

Here is the BNF for creating an access type to an object:

  access_object_type_declaration ::= "type" new_type_name "is"
                                    "access" ["all"] type_name ";"

Variables with an access type can either refer to an object or be null. You can make an access variable null by assigning it the value of the keyword "null", and you can check if it's null by comparing the variable (using "=" or "/=") to "null". Basically, you can treat "null" as a special value that any access type can store.

The ability to "point" at other values is useful and efficient, but it can also be dangerous. It's easy to do the wrong thing with pointers and cause surprising results. Ada tries to limit the damage that you can do while maintaining efficiency. Ada does this through the following rules:

The Ada compiler will optimize these checks and initializations away if it can determine that they're unnecessary. You can also turn off these checks for a given subprogram if you know that that particular subprogram is totally correct.

Now that we know how to declare access types, let's see how we can use them.


Quiz:

Which of the following will define an access type named Thing_Access?

  1. type Thing_Access is access Thing;
  2. type access is Thing_Access;
  3. Thing_Access is access type;

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 12 outline

David A. Wheeler (dwheeler@dwheeler.com)

The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s12s1.htm".