Thursday, August 16, 2007

C++ typesafe casting

Often, C++ classes are just casted to what is needed by

Subclass* sc = (Subclass)p;
This can lead to unexpected program behaviour, as no error is thrown in the case the p is not an instance of Subclass*; only a bit later, the programm will surely crash. Thus, the clean way is
Subclass* sc = dynamic_cast<SubClass*>(p);
of course, this requires run time type information; they should be available, if libstdc++ is available, too. This can also be used to determine the runtime type of a (class) pointer:
if (dynamic_cast<SubClass*>(p)) { ... }
Unfortunately, the C++ standard does not(?) provide any method to find out about class hierarchies ...

No comments: