Concepts of Programming Languages

(Sean Pound) #1
12.9 Support for Object-Oriented Programming in Ada 95 561

12.9.3 Dynamic Binding


Ada 95 provides both static binding and dynamic binding of procedure calls to
procedure definitions in tagged types. Dynamic binding is forced by using a
classwide type, which represents all of the types in a class hierarchy rooted at a
particular type. Every tagged type implicitly has a classwide type. For a tagged
type T, the classwide type is specified with T'class. If T is a tagged type, a vari-
able of type T'class can store an object of type T or any type derived from T.
Consider again the Person and Student classes defined in Section 12.9.2.
Suppose we have a variable of type Person'class, Pcw, which sometimes
references a Person object and sometimes references a Student object.
Furthermore, suppose we want to display the object referenced by Pcw, regard-
less of whether it is referencing a Person object or a Student object. This
result requires the call to Display to be dynamically bound to the correct
version of Display. We could use a new procedure that takes the Person type
parameter and sends it to Display. Following is such a procedure:

procedure Display_Any_Person(P: in Person) is
begin
Display(P);
end Display_Any_Person;

This procedure can be called with both of the following calls:

with Person_Pkg; use Person_Pkg;
with Student_Pkg; use Student_Pkg;
P : Person;
S : Student;
Pcw : Person'class;

...
Pcw := P;
Display_Any_Person(Pcw); -- call the Display in Person
Pcw := S;
Display_Any_Person(Pcw); -- call the Display in Student


Ada 95+ also supports polymorphic pointers. They are defined to have the
classwide type, as in

type Any_Person_Ptr is access Person'class;

Purely abstract base types can be defined in Ada 95+ by including the
reserved word abstract in the type definitions and the subprogram defini-
tions. Furthermore, the subprogram definitions cannot have bodies. Consider
this example:

package Base_Pkg is
type T is abstract tagged null record;
Free download pdf