Game Development Community

What's the difference between a static_cast and a dynamic_cast?

by Stefan Lundmark · in Torque Game Engine · 01/19/2006 (4:22 pm) · 4 replies

What's the difference between a static_cast and a dynamic_cast?

Searched the forums but get nothing that answers it.
Reason to me asking this is because I saw some code using dynamic_cast with a comment that said static_cast would be better for performance.

#1
01/19/2006 (4:26 pm)
Dynamic checks to make sure the object is in fact of the type you're casting it to,
static don't.


so

Foo* pFoo = new Foo();
Bar* pBar;

pBar = dynamic_cast<Bar*>pFoo;
// pBar is NULL here, good !

pBar = static_cast<Bar*>pFoo;
// pBar is not NULL here, bad !

so if you Know your cast is valid, use static.
#2
01/19/2006 (4:32 pm)
Then I'm clueless to this comment in guiCrosshairHud.cc:

Could mask against the object type here
and do a static cast if it's a ShapeBaseObjectType, but this
isn't a performance situation, so I'll just use dynamic_cast.
#3
01/19/2006 (4:44 pm)
MSDN info on static_cast vs dynamic_cast

The note is saying that performance isn't something that's critical in that particular portion of code, so it's "better" to use the safer dynamic_cast with runtime checking. You dont' list the actual code, so it's not positive that he's actually using the advantage of it being safer of course (checking to see if it fails).
#4
01/19/2006 (6:01 pm)
Thanks Stephen!

I assumed it was a TGE specific function. Thanks for clearing it up for me.