Article View: comp.lang.c++.moderated
Article #43Re: Pointer Typecasts
From: Frederic LACHASSE
Date: Fri, 02 Feb 1996 15:05
Date: Fri, 02 Feb 1996 15:05
59 lines
2436 bytes
2436 bytes
reckdahl@leland.Stanford.EDU (Keith Reckdahl) wrote:
>
> We've been having problems with the following pointer
> typecast: We have 4 classes A,B,C, and D
> B inherits from A
> C inherits from A
> D inherits from both B and C
> Note: We've have also tried to inherit D from B and C
> using the virtual keyword so that only one instance
> of A is instantiated, but this does not seem to affect
> the problem. We try to typecast a pointer from A to D
> meaning, in the code, we have
> A *a1;
> D *d1;
> d1 = (D *)a1;
> And this does not work. We get an illegal typecast
> compiler error. We've tried this on a variety of
> compilers, including CODE WARRIOR, BORLAND, and MPW.
>
> We thought that typecasting pointers is a simple
> matter because all pointers are simply addresses.
> What are we doing wrong?
Compilers are right: it's illegal. That's because they cannot know if
the pointer to A points to the B or C element of D:
< A
/ B <
| < B specific
|
| < A
D < C <
| < C specific
|
\ D specific
But the following should work:
d1 = (D *)(B *)a1;
d2 = (D *)(C *)a1;
with a different result of course.
If A is declared virtual in B and C, the problem is different: it is
illegal to cast a base virtual class to a derived class.
I don't have all my doc here, but may be dynamic_cast may work if you
have RTTI and virtual functions in A.
Fridiric LACHASSE (ECP 86)
CompuServe: 100530,2005
Internet: lachass@worldnet.fr
[ Articles to moderate: mailto:c++-submit@netlab.cs.rpi.edu ]
[ Read the C++ FAQ: http://www.connobj.com/cpp/cppfaq.htm ]
[ Moderation policy: http://www.connobj.com/cpp/guide.htm ]
[ Comments? mailto:c++-request@netlab.cs.rpi.edu ]
Technical Details
Message-ID:
<4et981$joh@netlab.cs.rpi.edu>Path:
arc1-ca.pugleaf.net!magnus.acs.ohio-state.edu!csn!ub!newserve!rebecca!rpi!not-for-mailReferences:
<4ejnr9$cpf@netlab.cs.rpi.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!magnus.acs.ohio-state.edu!csn!ub!newserve!rebecca!rpi!not-for-mail From: Frederic LACHASSE <lachass@worldnet.fr> Newsgroups: comp.lang.c++.moderated,comp.lang.c++ Subject: Re: Pointer Typecasts Date: 2 Feb 1996 15:05:37 -0000 Organization: World-Net information exchange, Internet provider. Sender: cppmods@netlab.cs.rpi.edu Approved: Dietmar.Kuehl@uni-konstanz.de Message-ID: <4et981$joh@netlab.cs.rpi.edu> References: <4ejnr9$cpf@netlab.cs.rpi.edu> Reply-To: lachass@worldnet.fr NNTP-Posting-Host: netlab.cs.rpi.edu X-Original-Date: Fri, 02 Feb 1996 13:39:13 +0000