Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

null_pointer

clear_cast<Head> ( thoughts )

This topic is 6716 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In case you can''t tell from the title, what do the C++ casting keywords (or operators?) do, specifically? I know of dynamic_cast, static_cast, const_cast, and reinterpret_cast. When should I use them and what restrictions are placed on them? The docs seems strangely silent about this. I do understand the syntax, though. Thanks in advance!
- null_pointer Sabre Multimedia

Share this post


Link to post
Share on other sites
Advertisement
Here''s the scoop:

dynamic_cast - for casting down an inheritance heirarchy. For example, you have a base class ptr and you want to know if it is a particular derived class, you use dynamic_cast, assuming you have RTTI and at least 1 virtual function ( which you should as in an inheritance heirarchy you should always make sure destructors are declared virtual )

static_cast - similar to the "C-style" cast - typically you''ll use this to convert longs to shorts or integer types to enums and stuff like that

const_cast - removes or adds const or volatile-ness - generally you should avoid const_cast as removing const-ness is usually akin to removing some of the safety you''ve designed into your classes. One use can be though if you have a const reference to an object that must return a portion of its representation to be placed into an existing API which expects a non-const ptr value, then you can use it there. but it may cause headaches

reinterpret_cast - converts pointers to integers and vice versa, and function ptrs to object ptrs and other scary stuff - generally you can probably avoid this

The February 2000 issue of C++ Report has an article on C++ cast operators - you may want to check it out

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!