Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!apple!netcom!teda!ditka!mcdchg!tellab5!balr!clrcom!rmartin From: rmartin@clear.com (Bob Martin) Newsgroups: comp.lang.c++ Subject: Re: type casting (ARM Experts needed.) Message-ID: <1991Feb11.184333.23382@clear.com> Date: 11 Feb 91 18:43:33 GMT References: Distribution: comp Organization: Clear Communications, Inc. Lines: 53 In article tomas@inmic.se (Tomas Lundstrom) writes: > >Hello, > >I'm not sure that my first posting made it, so I try again (sorry if >it is a duplicate). > >Suppose I have a class hierarchy > > A > / \ > / \ > B C > / \ > / \ > D E > >The descendants have no additional data, only additional functions. > >What I want is a 'universal object' that can be used for objects of >all classes in the tree. The question is: Can I use an 'A' object and >just cast it to the descendant classes ? ARM 5.4 says on this subject: A pointer to a class B may be explicitly converted to a pointer to a class D that has B as a direct or indirect base class if an unambiguous conversion from D to B exists (%4.6, %10.1.1) and if B is not a virtual base class (%10.1). Such a cast from a base to a derived class assumes that the object of the base class is a sub-object of an object of the derived class; the resulting pointer points to the enclosing object of the derived class. If the object of the base class is not a sub-object of an object of the derived, the cast may cause an exception. OK, what does this mean? ARM experts please check my interpretation... First the single inheritance case: It would appear that there is no problem casting a B* to a D* so long as the object being cast was initially created as a D or something derived from D. If you created the object as a B, then you may get an exception when you cast the B* to the D*. ARM does not indicate the conditions of when, or under what circumstances the exception does _not_ occur. It simply may cause an exception. The Multiple Inheritance case: In this case there may be no clear inheritance pathway to convert the B* to the D*. D may be reachable via many inheritance paths from B. In such a case the conversion is ambiguous and cannot be done. -- +-Robert C. Martin-----+:RRR:::CCC:M:::::M:| Nobody is responsible for | | rmartin@clear.com |:R::R:C::::M:M:M:M:| my words but me. I want | | uunet!clrcom!rmartin |:RRR::C::::M::M::M:| all the credit, and all | +----------------------+:R::R::CCC:M:::::M:| the blame. So there. |