Re: stroustrup, void*, and reinterpret_cast
Francis Glassborow wrote:
In article <c4dea$4503d67b$8259a2fa$5933@news2.tudelft.nl>, Lourens Veen
<lourens@rainbowdesert.net> writes
struct A { /* ... */ }
struct B { /* ... */ }
struct C : public A, public B { /* ... */ }
int main() {
C c;
C * cp = &c;
A * ap = static_cast<A *>(&c);
B * bp = static_cast<B *>(&c);
}
<snip>
In other words, the result of static_cast<B *>(&c) is a pointer of
type B * that points to c. The only difference between &c and
static_cast<B *>(&c) is that the type of the first expression is C *,
and the type of the second expression is B *. Their _value_ is the
same, namely "pointer to c", their types are different.
Sorry, IMHO that way madness lies. bp is a pointer to some B object or
subobject. The above code initialises it to a subobject of c. But we can
latter change it to point to some other B object. It does not inherently
point into a C object.
At best, after the initialisation above we can say that bp points into
c. Note that I can make the problem even more severe by using a virtual
base class.
I think it depends on the style of the code. If B was designed as a
polymorphic base class (or interface), surely the only valid way to
think of bp is that it 'points to c'. I think the normal way of writing
the code:
B* bp = &c;
says that pretty clearly.
It does rely on B and C conforming to OO conventions, and of course
there are other ways of using inheritance in C++, such as
implementation (boost::iterator_facade is my favourite example). In
those cases, though, you wouldn't normally have a pointer or reference
to base in client code. The base is just an implementation detail (and
the compiler-provided conversion unfortunate, but not a problem in
practice).
James
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]