Intermediate C++ Game Programming Tutorial 19
From Chilipedia
In this video Chili teaches us how to figure out what our polymorphic pointers are actually pointing to (aka "type discovery"). Just note that although we can do this, it is generally a weaksauce way to go about things. Virtual functions are 1000% more hype than type discovery bullshit. Oh yeah, we also finally see all the C++ style casts united.
Topics Covered
-
dynamic_cast<T*>
anddynamic_cast<T&>
-
const_cast
- Overview of all C++ style casts
- RTTI with
typeid()
- The
type_info
class
Video Timestamp Index
[Expand]
- Using
dynamic_cast<new-type>(expression)
to determine to what derived type a pointer to a polymorphic base type is actually pointing 0:54
- Using
static_cast<>()
to convert pointers within an inheritance hierarchy 6:20
- Using
const_cast<>()
to remove a const from a reference or pointer (yes, you read that right) 7:27
- Overview of different types of casts 9:30
[Expand]
- static_cast
- dynamic_cast
- casts pointers/references within an inheritance hierarchy (dynamic check!)
- requires that the type have at least one virtual function
- if check fails, nullptr for ptr* cast, throw exception for ref& cast
- reinterpret_cast
- reinterpret pointers/references as pointing to some other type (no check, no limit!) (only really safe for char*)
- reinterpret pointer as an integral value
- const_cast
- remove constness
- c-style cast (int) etc.
- can do all of the above, even if you don't mean to
const Base* pBase = &obj;
- ...
Derived* pDerived = (Derived*)pBase;
- casted away the constness by accident!
- can do all of the above, even if you don't mean to
- dynamic_cast
- Using RTTI (Runtime Type Information) 13:01
- To use RTTI, include
<typeinfo>
and use operatortypeid()
to obtain the type id of any dynamic type - Use case: check if two objects are of the same derived class:
if( typeid(f1) == typeid(f2) )
-
typeid()
returns an object of typestd::type_info
- To use RTTI, include
- The
type_info
class 15:05
- Get the type name of an object by calling
typeid(obj).name()
- You can't use typeid in switch statements, but you can use them in map class to get similar functionality
- typeid does have an overhead, like dynamic_cast, so avoid its use in super performance critical applications
- Get the type name of an object by calling
- Main take-away 16:40
- You can discover a dynamic type at runtime and act on that, but it is much more elegant to avoid this and use dynamic dispatch (smart design of virtual functions that dispatch to the correct implementation) to do this for you
- Use virtual functions to their full effect. Only as a last resort, try to discover the underlying type and act on it
Source Code
Note that the code for this video is in a different branch called "casting". You will not find it in the master branch.