comp.lang.ada
 help / color / mirror / Atom feed
From: franke@minet.uni-jena.de (Frank Ecke)
Subject: Re: Constructors?
Date: 1998/08/25
Date: 1998-08-25T00:00:00+00:00	[thread overview]
Message-ID: <slrn6u4oir.1pf.franke@pax10f.mipool.uni-jena.de> (raw)
In-Reply-To: 35DF0616.77764632@tech.swh.lv

On Sat, 22 Aug 1998 20:55:34 +0300, Maxim Senin <maks@tech.swh.lv> wrote:

>I'm new to ADA. I'm looking for tips/tricks on how to write constructors. As I
>understand, in ADA I have to rewrite constructor completely for each subclass.
>How can I reduce code duplication? Can superclass constructor be called from
>descendent class constructor?

Use the name Ada, please.

Yes, you can call a superclass constructor from a descendent class constructor.
But beware, although the term constructor exists in Ada, it should not be
confused with the notion used in OO.  For example, in Java, constructors are
not inherited by the subclass.  In Ada, a constructor is simply a primitive
operation of a tagged type and, therefore, it is propagated into the subclass.
Consider, for illustration, a simple hierarchy of geometrical figures (Point,
Circle, Rectangle, etc.):

type Colored_Point is tagged limited record
   This_X : Float := 0.0;
   This_Y : Float := 0.0;
   This_Color : Color_Type := Black;
end record;


type Rectangle is new Colored_Point with record
   This_Length, This_Width : Natural := 1;
end record;


procedure Init_New_Colored_Point(
  This_Figure : in out Colored_Point;
  Init_X, Init_Y : Float := 0.0;
  Init_Color : Color_Type := Black) is

begin
   Set_XY(This_Figure, Init_X, Init_Y);
   Set_Color(This_Figure, Init_Color);
end Init_New_Colored_Point;


procedure Init_New_Rectangle(
  This_Figure : in out Rectangle;
  Init_X, Init_Y : Float := 0.0;
  Init_Color : Color_Type := Black;
  Init_Length, Init_Width : Natural := 1) is

begin
   Init_New_Colored_Point(
     Colored_Point(This_Figure),  -- effectively ignore the Rectangle
                                  -- components
     Init_X, Init_Y,
     Init_Color);  -- calls the ``constructor'' of the superclass
   This_Figure.This_Length := Init_Length;
   This_Figure.This_Width := Init_Width;
end Init_New_Rectangle;


Note that since Init_New_Colored_Point is inherited by Rectangle, there is the
risk of mixing up the various constructor calls.  A bit of care is needed.


Hope this helps.


Regards,


Frank




       reply	other threads:[~1998-08-25  0:00 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
     [not found] <35DF0616.77764632@tech.swh.lv>
1998-08-25  0:00 ` Frank Ecke [this message]
1998-08-25  0:00   ` Constructors? Tucker Taft
1998-08-27  0:00   ` Constructors? Matthew Heaney
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox