From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.4 X-Google-Thread: 103376,e1e2bc096a996632,start X-Google-Attributes: gid103376,public X-Google-Language: ENGLISH,ASCII-7-bit Path: g2news1.google.com!postnews.google.com!not-for-mail From: gate02@wrandyke.demon.co.uk (Michael Mounteney) Newsgroups: comp.lang.ada Subject: why can't we declare unconstrained objects ? Date: 12 Dec 2004 07:43:21 -0800 Organization: http://groups.google.com Message-ID: NNTP-Posting-Host: 80.176.143.194 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-Trace: posting.google.com 1102866202 26117 127.0.0.1 (12 Dec 2004 15:43:22 GMT) X-Complaints-To: groups-abuse@google.com NNTP-Posting-Date: Sun, 12 Dec 2004 15:43:22 +0000 (UTC) Xref: g2news1.google.com comp.lang.ada:6901 Date: 2004-12-12T07:43:21-08:00 List-Id: Is there a simple way in Ada of simulating C/C++ unions ? It seems to me that this is gratuitously prevented, that is, it can be done with safety, by extending an existing run-time check, but it is in fact prevented by the compiler. Hopefully the following commented source will illustrate my point. with Ada.text_IO; procedure unconstrained is -- Very simple discriminated type type thing (what : Boolean) is record case what is when false => letter : character; when true => number : natural; end case; end record; -- No problems here: we provide a discriminant. sample : thing := (false, 'X'); -- This is alright as well of course. type thing_pointer is access all thing; -- This is also fine: a pointer to any `thing'. indirect : thing_pointer; -- This causes a problem: I want an unconstrained `thing', one -- that can be switched between holding a character and a number -- but the initialisation makes it constrained. sample2 : thing := (true, 12); -- Omitting the initialisation doesn't work: -- this just fails at compile-time. sample3 : thing; begin -- Just reference a field in the `thing'. Ada.text_IO.put (sample.letter); -- Create a new access object and access its field -- This requires a RUN-TIME check that indirect.what is true. indirect := new thing (true); indirect.number := 12; -- This will generate a RUN-TIME failure of course. indirect.letter := 'A'; -- Warning at compile-time, failure at run-time. I want to change the -- discriminant. Since the compiler will insert a run-time check -- for field selection via an access, why not for a direct variable ? sample2 := thing'(false, 'Z'); end;