To create a controlled type, simply declare it as a descendent of the either the type "Controlled" or the type "Limited_Controlled" from 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 execute "Adjust" after the normal assignment Ada will perform.
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 (self-assignment is a well-known source of bugs in C++). More precisely, Ada must act as though the following steps were performed when "A := B" is executed:
The phrase "act as though" is very important; most compilers will optimize away the intermediate anonymous object, 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 LRM.
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 (wheeler@ida.org)