[   ^ to index...   |   next -->   ]

CSE 143/AC : 27 July 2000


Further C++ casts

I was lying when I told you it was illegal to "downcast" pointers from a superclass pointer to a subclass pointer. In reality, C++ provides three special kinds of casts besides const_cast, and one of them serves specifically to allow downcasts between pointer types in a safe manner.

static_cast and dynamic_cast

static_cast is a general replacement for old C-style casts between primitive types. It can also be used to downcast certain kinds of class pointers. However, in the latter case, there is no checking whatsoever to make sure the dynamic object really is of the proper type.

int x; double y = static_cast<double>(x); void foo( Mammal * creature ) { // dog is undefined if creature does not point to a Canine Canine * dog = static_cast<Canine *>( creature ); }

Therefore, you should only use static_cast when you are certain that the cast will be safe. (In other words, static_cast is dangerous.) For less certain situations, you need dynamic_cast:

void fixed_foo( Mammal * creature ) { Canine * dog = dynamic_cast<Canine*>( creature ); if (dog == NULL) { // error, or treat creature as a Mammal } else { // dog code } }

reinterpret_cast

The most evil cast in the known universe, reinterpret_cast means "cast from anything to anything, with implementation-dependent results." Most often used for low-level hardware hacking, where it may be necessary.


Last modified: Thu Jul 27 01:20:58 PDT 2000