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.3 required=5.0 tests=BAYES_00,INVALID_MSGID autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,3d313337c39c5dd5 X-Google-Attributes: gid103376,public From: Matthew Heaney Subject: Re: run-time type identification Date: 1998/09/03 Message-ID: #1/1 X-Deja-AN: 387479834 Sender: matt@mheaney.ni.net References: <01bdd72e$49ee66b0$f330ea9e@ukp03332> NNTP-Posting-Date: Thu, 03 Sep 1998 06:48:50 PDT Newsgroups: comp.lang.ada Date: 1998-09-03T00:00:00+00:00 List-Id: "Bob Fletcher" writes: > Is there any equivalent in Ada 95 to the C++ "dynamic_cast" operator? > > For example, say you have a class A, and a derived class A2. > In the package for class A there is also: > type A_Ptr is access A'Class; > You can assign an access to an object of class A2 to a variable of type > A_Ptr, but, as far as I know, cannot then de-reference the A_Ptr in such a > way that the extra bits of class A2 are accessible. The syntax is just a normal type cast: procedure Op (O : A_Ptr) is O2 : A2 renames A2 (O.all); begin This is called a "view conversion." It gives you an A2 view of object O. Of course, if O's type isn't in A2'Class, then you'll get Constraint_Error. If you call operations on O2, you'll be calling the primitive operations for the specific type A2. However, you probably want to the operations to dispatch. After all, the object might be of a specific type that derives from A2: procedure Op (O : A_Ptr) is O2 : A2'Class renames A2'Class (O.all); begin This is a view conversion to the class-wide type A2'Class. You always have membership test available to you: if O.all in A2 then ...; if O.all in A2'Class then ...; > It seems to me that this is something that would make a lot of sense when > dealing with class-wide access types, which can easily be used to go up the > object heirarchy, but not, as far as I know, to go back down, (without > messing about with unchecked_conversion). A downcast from a class-wide type nearer the root to a type (specific or class-wide) more away from the root is perfectly legal in Ada95. No Unchecked_Conversion is necessary.