// Casting is evil. If you use it, somebody’s done something wrong. // // C++ casting: // - dynamic_cast (expression) // Convert (downcast) a base type pointer to a derived type. // Yields nullptr when you’re wrong. Not needed for the other direction. // // - static_cast (expression) // Upcast/downcast pointers, and perform implicit conversions. // // - const_cast (expression) // Remove constness. // // - reinterpret_cast (expression) // Convert anything to anything--used by lunatics. // // C casting: // - (type) expression // Same as reinterpret_cast; avoided by savvy C++ programmers. // // Casting does not read your mind. Consider (int) "123". class Animal { virtual bool has_gills() = 0; }; class Fish : public Animal { bool has_gills() { return true; } }; int main() { Fish nemo; Animal *ap = &nemo; // no cast needed Fish *fp = dynamic_cast(ap); // Runtime error checking fp = static_cast (ap); // No error checking char *cp = const_cast("Hello"); // const char * to char * double *dp = reinterpret_cast(&nemo); // Fish * to double * ?? return !fp+!cp+!dp; // Way too cute. }