Article View: comp.std.c++
Article #3313Re: casting and virtual inheritence
From: jodle
Date: Fri, 09 Feb 1996 15:38
Date: Fri, 09 Feb 1996 15:38
49 lines
2374 bytes
2374 bytes
David Sachs (b91926@fsgm01.fnal.gov) wrote:
: First of all, I think (B*A) or dynamic_cast<B*>(A) is not a valid
: expression, because A is a type name rather than a variable name. I
: assume you meant dynamic_cast<B*>(a1)... In this case the semantics
: are:
: class A {};
: class B : public virtual A {};
: int main()
: {
: A* a1 = new A;
: A* a2 = new B;
: B* b1 = dynamic_cast<B*>(a1); // b1 == NULL, because there is no B
: B* b2 = dynamic_cast<B*>(a2); // points to a2 as a B
: return 0;
: }
I think the question "why?" remains unanswered. The answer itself is
quite simple. If B virtually inherits A, each object instantiated from
class B contains (or acts as if it contains) a pointer to the base class A
part of itself. It is not possible to downcast from an A to a B because
we have no way of knowing for sure where the supposed B associated with A
really is. To illustrate, the data parts of our B might looks something
like this:
class B
{
A *virtualBaseClassA;
};
In contrast, if we have nonvirtual inheritance we (may, depending on the
compiler) know that A and B both have the same address (but different
sizes) in memory. This looks something more like:
class B
{
A nonvirtualBaseClassA;
};
I don't view downcasting as the best thing to do, generally. I have to
say that the cast operators at least give us a way to do it that allows us
to detect when the cast didn't work. Without them, downcasting just gives
you a pointer to some stuff that may or may not be what you think it
should be.
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. Moderation policy:
http://reality.sgi.com/employees/austern_mti/std-c++/policy.html. ]
Technical Details
Message-ID:
<4fedrp$904@news2.delphi.com>Path:
arc1-ca.pugleaf.net!in2.uu.net!bounce-backReferences:
<4fbt35$9ej@fido.asd.sgi.com> <4fdulf$34p@fsgm01.fnal.gov>Show Full Headers
Complete Article Headers
From: jodle@bix.com (jodle) Message-ID: <4fedrp$904@news2.delphi.com> X-Original-Date: 9 Feb 1996 03:08:41 GMT Path: arc1-ca.pugleaf.net!in2.uu.net!bounce-back Date: 09 Feb 96 15:38:29 GMT Approved: fjh@cs.mu.oz.au Newsgroups: comp.std.c++ Subject: Re: casting and virtual inheritence Organization: BIX References: <4fbt35$9ej@fido.asd.sgi.com> <4fdulf$34p@fsgm01.fnal.gov> X-Newsreader: TIN [version 1.2 PL2] X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUBMRtqhuEDnX0m9pzZAQFyBAF7BhSa4WGaejJBPrg3VpLGU1cYCFln0i4w EEiPKq+iWZdZvlp+Xy2Z5DU2JjtNRhrk =4pFN