C++ Type Casting

From Schmid.wiki
Jump to: navigation, search

Casting

dynamic_cast     - type-safe casting (normally, you should use this!)
const_cast       - ignore const or volatile
reinterpret_cast - hard, evil cast to an unrelated type
static_cast      - well-defined conversions (no idea what it is)

Example usage:

float* y;
int* x = reinterpret_cast<int*>(y);

Using dynamic_cast:

Derived derived;
Base *base_ptr = &derived;

Derived *d = dynamic_cast<base_ptr>(Derived *);
if(d)                                            // <- This is the important point:
    d->derived_method();                         //    d is NULL if it isn't a pointer
                                                 //    to an instance of Derived.
Personal tools