fork download
  1. #include <iostream>
  2. #include <typeinfo>
  3.  
  4. class Shape { public: virtual ~Shape() {}; };
  5. class Circle : public Shape {};
  6. class Square : public Shape {};
  7. class Other {};
  8.  
  9. int main() {
  10. Circle c;
  11. Shape* s = &c; // Upcast: normal and OK
  12. // More explicit but unnecessary:
  13. s = static_cast<Shape*>(&c);
  14. // (Since upcasting is such a safe and common
  15. // operation, the cast becomes cluttering)
  16. Circle* cp = nullptr;
  17. Square* sp = nullptr;
  18. // Static Navigation of class hierarchies
  19. // requires extra type information:
  20. // C++ RTTI
  21. if (typeid(*s) == typeid(Circle))
  22. cp = static_cast<Circle*>(s);
  23. if (typeid(*s) == typeid(Square))
  24. sp = static_cast<Square*>(s);
  25. std::cout << "cp = " << cp << std::endl;
  26. std::cout << "sp = " << sp << std::endl;
  27. if (cp) std::cout << "It's a circle!" << std::endl;
  28. if (sp) std::cout << "It's a square!" << std::endl;
  29. // Static navigation is ONLY an efficiency hack;
  30. // dynamic_cast is always safer. However:
  31. // Other* op = static_cast<Other*>(s);
  32. // Conveniently gives an error message, while
  33. // that would be undefined behavior (UB)!
  34. // Other* op2 = (Other*)s;
  35. // does not
  36. // AND *nothing* is guaranteed if we uncomment the UB
  37. // INCLUDING *anything* about the lines *before* the UB (yes, really!)
  38. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
cp = 0xbff0ab6c
sp = 0
It's a circle!