Section 7.6 - Abstract Types and Subprograms

It's often useful to declare a tagged type that won't be used directly to create objects, but instead will be extended by different types in different ways. Such types are called ``abstract'' types.

Abstract types must be tagged types, since only tagged types can be extended. To define an abstract type, simply put the keyword abstract in front of the keyword tagged in its definition.

Subprograms can also be declared as abstract; a call to such subprograms would have to dispatch to an overridden version of the subprogram. To declare a subprogram as abstract, place the phrase "is abstract" before the last semicolon in its definition. If you have an abstract subprogram for a given type, the type must also be abstract.

When you later create another type that descends from an abstract type, you must define all of its abstract subprograms.

Here's an example of an abstract type representing a set of natural numbers, taken directly from the Ada RM section 3.9.3:

  package Sets is
    subtype Element_Type is Natural;
    type Set is abstract tagged null record;
    function Empty return Set is abstract;
    function Union(Left, Right : Set) return Set is abstract;
    function Intersection(Left, Right : Set) return Set is abstract;
    function Unit_Set(Element : Element_Type) return Set is abstract;
    procedure Take(Element : out Element_Type; From : in out Set) is abstract;
  end Sets;

Given the above abstract type, you could then derive various (nonabstract) extensions of the type, representing alternative implementations of a set. You might use a bit vector, but impose an upper bound on the largest element representable, while another might use a hash table, trading off space for flexibility.

Abstract subprograms are equivalent to ending a C++ function declaration with ``= 0''.


There is no quiz question for this section.

You may go to the next section.


You may also:

PREVIOUS Go back to the previous section

OUTLINE  Go up to the outline of lesson 7

David A. Wheeler (dwheeler@dwheeler.com)

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