Advertisement

clear_cast<Head> ( thoughts )

Started by March 29, 2000 05:03 PM
1 comment, last by null_pointer 24 years, 8 months ago
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
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
Advertisement
Now everything makes sense!

Thanks!


- null_pointer
Sabre Multimedia

This topic is closed to new replies.

Advertisement