disp() doesn’t access any of the members of the class, it is in principle the same as if it were declared in the global namespace instead of in class, so there are no negative side effects to calling it, even though the instance is not of the right class.
What are you doing is downcasting a pointer of a base class to a pointer of the derived class, even though it was not initialized as such. If
disp() tried to access class members that were in
D but not in
B, you would probably run into segfaults.
Bottom line: don’t use
static_cast for downcasting unless you’re absolutely sure the pointer is actually pointing to an instance of the derived class. If you’re unsure, you can use
dynamic_cast which fails in the event of mismatch (but there is the overhead of RTTI, so avoid it if you can).
dynamic_cast will return
nullptr if the cast is incorrect or throw a
std::bad_cast exception if it casts references, so you will know for sure why it fails instead of possible memory corruption bugs.
Originally posted 2013-11-09 23:19:47.