Section 12.5 - Access Parameters (For Object Orientation)
Often when developing object-oriented systems
you will want to pass around access values to tagged types
(we discussed tagged types in lesson 7).
Ada 95 adds a new pseudo-mode called "access" to help you build OO
systems using access types.
If you recall, every parameter for a subprogram has to be of mode
in, in out, or out.
You can use the keyword "access" as a mode (followed by a type name) instead.
Here's an example:
procedure Get(Agent : access Occupant; Direct_Object : access Occupant'Class);
So what in the world does this example mean??
Here's the answer:
-
When an "access mode" is followed by an ordinary tagged type,
it means that the input parameter (in this case Agent) must be
an access value of the given type (in this case Occupant).
More importantly, this procedure can be overridden, and the
type of the object being accessed will determine which subprogram
to dispatch to.
Thus, we could create another subprogram called "Get" for a descendent
of Occupant, and that subprogram Get would override the Get defined here.
This is an essential part of being an OO language - we can dispatch to
a given program using the current data value.
Access parameters let us dispatch using the access value.
-
When an "access mode" is followed by a class type,
it means that the input parameter (in this case Direct_Object) must be
an access value of the given type (in this case Occupant) or any
of its descendents.
In this case we do not dispatch on this parameter,
since any of the descendents will do for this subprogram.
In this case, access parameters let us accept a wide range of types,
instead of just a specific access type.
There's an important requirement for access parameters - null values are
not permitted.
If you want to permit null values, use the modes in, out, or in out with
an ordinary access type.
It's difficult to understand access parameters
without more context, so we'll defer discussing this further until
lesson 18 where we will
look at examples of this.
What you need to understand right now is that if you're using access types
and object-oriented programming, you will probably want to use
the pseudomode "access".
Quiz:
Given the following procedure declaration:
procedure Jump(E : access Occupant'Class);
Will a call to procedure Jump dynamically dispatch to one of many
subprograms depending on the exact type of "E"?
- Yes, Jump will dynamically dispatch.
- No, Jump will not dynamically dispatch.
You may also:
David A. Wheeler (dwheeler@ida.org)