Note that Ada 95 has a more specific meaning for ``class'' than some other object-oriented programming languages (such as C++). In C++, the term class may mean either ``a specific type'' or ``the set of a specific types and all types that inherit from it, directly and indirectly.'' Ada 95 uses different terms for these different concepts.
A subprogram can define one or more parameters as a type of the form T'Class. Whenever the subprogram is called, it simply takes on the value of whatever was passed to it. But what happens if that subprogram then tries to call some other subprogram that requires a specific type? The answer is dynamic dispatching. Ada will take the tag associated with the tagged type and determine at run-time which routine to call.
This is easier shown than explained. Let's say that we want to create a subprogram that takes in a value of any type derived from Alert. The subprogram is to print out the phrase "processing alert" and then call the correct Handle subprogram for the given Alert type. Here's an example of how to do that:
procedure Process_Alert(AC : in out Alert'Class) is begin Put_Line("Processing Alert."); Handle(AC); -- Dispatch to "correct" Handle. end Process_Alert;
When the Ada program reaches the Handle statement, it will note that the current type is a Class type, and that Handle takes only a specific type, and so it will dispatch to the correct Handle operation depending on its type.
Dispatching will only occur on subprograms that were defined in the same package as the tagged type itself. These subprograms are formally called primitive subprograms.
package Critters is type Monster is tagged record Size_In_Meters : Integer; end record; type Dragon is new Monster with null record; type Red_Dragon is new Dragon with null record; type Person is tagged record Age : Integer; end record; end Critters;
How many different types does Monster'Class include in package Critters?
Go back to the previous section
Go up to the outline of lesson 7
David A. Wheeler (wheeler@ida.org)