reinterpret_cast or static_cast ?

L

Lucy Ludmiller

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 ?
 
A

Alf P. Steinbach

* 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.
 
D

dasjotre

Alf said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top