* Lucy Ludmiller:
I have two classes:
class base { ... };
and
class derived : public base { ... };
I have a function :
void foo(const base*) { ... }
If a nullvalue for the pointer is not meaningful, make that
void foo( base const& )
I want to be able to cast back to derived (I only have a ptr to base in
this compilation unit), and then invoke a method on object derived
Then make that
void foo( derived const& )
- do I use a static_cast or reinterpret_cast to cast "upward" ?
static_cast or dynamic_cast.
If base has one or more virtual member functions, make that
dynamic_cast. Choose casting of reference for exception, or casting of
pointer + assert for assertion. Be sure to test that piece of code
extremely thoroughly.
Or (much!) better, design the cast away.
- any reason why one is a better choice than the other ?
They're different. Conceptually a reinterpret_cast reinterprets the
bits of the pointer value as some other pointer type, without doing
necessary adjustments. In this context reinterpret_cast yields
undefined behavior.
Generally (there is one exception) you can only use the result of a
reinterpret_cast in a portable way by casting back to the original type.
For someone who is unsure of casting, reinterpret_cast means you have a
bug, and any cast whatsoever means you have a potential set of bugs.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?