Defaults for these operations are provided by Ada. If you want more control over these operations, you can declare objects to be a controlled type.
To create a controlled type, simply declare it as a descendent of either the type "Controlled" or the type "Limited_Controlled"; these types are defined in the predefined package "Ada.Finalization". Use "Controlled" when you want control over all three operations, and use "Limited_Controlled" when you don't want control over assignment.
Here's a partial definition of Ada.Finalization:
type Controlled is abstract tagged private; procedure Initialize(Object : in out Controlled); procedure Adjust (Object : in out Controlled); procedure Finalize (Object : in out Controlled); type Limited_Controlled is abstract tagged limited private; procedure Initialize(Object : in out Limited_Controlled); procedure Finalize (Object : in out Limited_Controlled);
Once you've created your own type that's descended from Controlled or Limited_Controlled, you can override Initialize, Adjust, or Finalize to do whatever you want. Whenever an object of your type is created, Ada will do its own initializations and then call the routine "Initialize" that you have defined. Whenever an object of your type is about to be destroyed (say, by exiting the subprogram it was defined in), the "Finalize" routine will be executed.
If you use a descendent of type Controlled, you can control assignment (:=) as well. Then, when Ada executes a statement like "A := B;", Ada will first perform the normal assignment and then execute "Adjust".
Some people (particularly those familiar with C++) will ask, ``what happens if you assign a variable to itself, like A := A''? Ada handles this correctly due to a careful definition of assignment involving a conceptual "anonymous object" (self-assignment is a well-known source of bugs in C++). Most compilers will optimize away the intermediate anonymous object in most cases, and may do many other optimizations as well.
User defined initialization, assignment and finalization are defined in great detail in section 7.6 of the Ada RM.
The types Controlled and Limited_Controlled are particularly useful for implementing types whose "size" can vary without limit (these types are called "unbounded" types). We'll learn more about them in the later lesson on access types.
There is no quiz question for this section.
You may go to the next section.
|Go back to the previous section||Go up to the outline of lesson 7|
David A. Wheeler (firstname.lastname@example.org)
The master copy of this file is at
The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s7sf.htm".