Skip to main content
gamedev.net
🔒 Locked

dynamic_cast

Started by peter86 3 replies 200+ views
Original Post
peter86
peter86
How does dynamic_cast differentiate from static_cast and reinterpret_cast?
Fruny
Fruny
reinterpret_cast is used to ... reinterpret the bit pattern as another type, without modification. While using static_cast to convert a float to an int would truncate, reinterpret_cast would just transfer the bits an read them as if it had been an int all along.

static_cast is a close relative of the C cast, with the exception that C casts can be reinterpret_casts in some cases. It is used when the actual types are known at compile-time.

dynamic_cast is used to safely downcast from a polymorphic Base (must have a virtual function) to a Derived type when you''re not sure the object really is of the Derived type. See below.


Base *pBase = new Base; // pointer to Base, Base object
Base *pDerived = new Derived; // pointer to Base, Derived object

Derived* pD0 = static_cast(pBase);
// BOOM ! pBase doesn''t point to a Derived object

Derived* pD1 = static_cast(pDerived):
// Ok. pDerived really pointed to a Derived object

Derived* pD0 = dynamic_cast(pBase);
// pD0 will be set to NULL, you can test for it.

Derived* pD1 = dynamic_cast(pDerived):
// Ok. pDerived really pointed to a Derived object




[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
civguy
civguy
Fruny, you''re being all too helpful. Google is the right answer for questions this generic
Fruny
Fruny
You''re probably right


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
DerekSaw
DerekSaw
... and you need RTTI support to use dynamic_cast
"after many years of singularity, i'm still searching n the event horizon" o

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.