comp.lang.ada
 help / color / mirror / Atom feed
From: Robert A Duff <bobduff@shell01.TheWorld.com>
Subject: Re: Changing default values in derived types
Date: Sun, 30 Aug 2009 12:07:14 -0400
Date: 2009-08-30T12:07:14-04:00	[thread overview]
Message-ID: <wccy6p1p9ot.fsf@shell01.TheWorld.com> (raw)
In-Reply-To: 18c7529c-1dcb-416d-a1ae-71a713ebed45@n2g2000vba.googlegroups.com

vlc <just.another.spam.account@googlemail.com> writes:

> is there a way to change a default value upon type derivation?
>
> type PT is tagged record
>    V : Float := 1.0;
> end record;
>
> type CT is new PT with null record;
>
> Is there a way to use another default value for V in CT?

No, not directly.

But you could do something like this:

  package PTs is

     type PT (<>) is tagged private;
     function Make return PT;

  private
     type PT is tagged
        record
           V : Float;
        end record;
  end PTs;

  package body PTs is

     function Make return PT is
     begin
        return (V => 1.0);
     end Make;

  end PTs;

  package PTs.CTs is

     type CT (<>) is new PT with private;
     function Make return CT;

  private
     type CT is new PT with null record;
  end PTs.CTs;

  package body PTs.CTs is

     function Make return CT is
     begin
        return (V => 1_000.000_001);
     end Make;

  end PTs.CTs;

  with PTs.CTs; use PTs; use PTs.CTs;
  procedure Main is
     X : PT := Make; -- Initialize V to 1.0.
     Y : CT := Make; -- Initialize V to 1_000.000_001.
  begin
     null;
  end Main;

The (<>) on the type declarations means "clients are not allowed to
create uninitialized objects".  So "X : PT;" is illegal in Main.
Main is forced to explicitly initialize, and the only way to
get a value is to call Make.

You might want to call them Make_PT and Make_CT, but then you wouldn't
want them to be primitive -- either have them return the class-wide
type, or declare them in nested packages.

I think default values are a questionable feature anyway,
so I'd generally prefer something like the above.  And in Ada 2005,
it even works for limited types.

>...I already
> tried with controlled types using different Initialize procedures, but
> that's quite ugly.

And fairly expensive, on most implementations, although AdaCore is
working on making controlled types more efficient.

> Thanks a lot in advance!

You're welcome.

- Bob



  reply	other threads:[~2009-08-30 16:07 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2009-08-30 15:05 Changing default values in derived types vlc
2009-08-30 16:07 ` Robert A Duff [this message]
2009-08-30 19:41   ` vlc
replies disabled

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