470,571 Members | 2,344 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,571 developers. It's quick & easy.

reinterpret_cast or static_cast ?

I have two classes:

class base { ... };

and

class derived : public base { ... };
I have a function :

void foo(const base*) { ... }

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

- do I use a static_cast or reinterpret_cast to cast "upward" ?
- any reason why one is a better choice than the other ?

Sep 3 '06 #1
2 2423
* 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?
Sep 3 '06 #2

Alf P. Steinbach wrote:
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 boost::polymorphic_downcast

Sep 7 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by Scott Brady Drummonds | last post: by
15 posts views Thread by Aman | last post: by
5 posts views Thread by Christopher Benson-Manica | last post: by
3 posts views Thread by Nate Barney | last post: by
27 posts views Thread by Noah Roberts | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.