O
Old Wolf
If C is derived from A & B, then a C object IS an A and IS a B. At the
same time.
Yes, but an A is not a B. The two are unrelated
except in that they are both part of a C. If
you are pointing to an A, then the only way you
are going to be able to point to a related B is
if you know you are actually pointing to an A
sub-object of a C. Which is why this doesn't work
if you are using a pointer to void, which contains
no type information.
// quick recap: class C is derived from both class A and B
A *ap;
B *bp;
C c,*cp;
cp=&c;
ap=cp;
bp=(B*)ap;
This is a reinterpret-cast, because A and B are unrelated
types (see above). The pointer 'ap' has lost the information
that it is actually pointing to an A that's a subobject
of a C.
or the last line being
bp=static_cast<B*>(ap);
Should be a compliation error for the above reason.
You can perform the conversion successfully:
bp = dynamic_cast<B *>(ap);
which tells the compiler to find the biggest object
that *ap is a sub-object of, and then try to find a
B object within that object. This is sometimes
called cross-casting.
Note, I'm not entirely sure about this, but I think
this only works if A and B are both polymorphic
classes, that is, they both contain at least one
virtual function (which will usually be the virtual
destructor). You might just get a null pointer if
this requirement is not met.