Should I be using dynamic_cast or c-style casting here...

  • Thread starter Thread starter 0to60
  • Start date Start date
0

0to60

I'm coding in MC++ and I'm using the System::Collections data structures to
store my own objects. When I get something out of a hashmap, should I be
using dynamic_cast or old C-style casting? In other words, should it be

Namespace::ObjectName* someObject =
(Namespace::ObjectName*)hashMap->Item(key);

or

Namespace::ObjectName* someObject =
dynamic_cast<Namespace::ObjectName*>(hashMap->Item(key));
 
0to60 said:
I'm coding in MC++ and I'm using the System::Collections data
structures to store my own objects. When I get something out of a
hashmap, should I be using dynamic_cast or old C-style casting? In
other words, should it be

Namespace::ObjectName* someObject =
(Namespace::ObjectName*)hashMap->Item(key);

or

Namespace::ObjectName* someObject =
dynamic_cast<Namespace::ObjectName*>(hashMap->Item(key));

Depends whether you want safety or speed. If you "know" what kind of object
it is, go ahead and use the C-style cast (or use static_cast). If there's a
chance that some other kind of object is present, use dynamic_cast.

A common idiom is to use something like this:

assert(dynamic_cast<NameSpace:::ObjectName*>(hashMap->Item(key));

Namespace::ObjectName* someObject =
static_cast<Namespace::ObjectName*>(hashMap->Item(key));

-cd
 
C-style cast on managed types in MC++ translates into a __try_cast, so it is
equally as safe as dynamic_cast.

Ronald Laeremans
Visual C++ team
 
Ronald Laeremans said:
C-style cast on managed types in MC++ translates into a __try_cast, so it is
equally as safe as dynamic_cast.

Interesting. How about static_cast<>? Does that translate into a
__try_cast also?
 
Back
Top