fork download
  1. #include <iostream>
  2. #include <typeinfo>
  3.  
  4. struct Base
  5. {
  6. virtual void test() { /* ... */ }
  7. };
  8. struct Derived : Base
  9. {
  10. virtual void test() { /* ... */ }
  11. };
  12.  
  13. int main()
  14. {
  15. Base *bp = new Base;
  16.  
  17. // null if dynamic_cast is invalid
  18. if (Derived *dp = dynamic_cast<Derived*>(bp) )
  19. {
  20. std::cout << "Dynamic cast with pointer succeeded" << std::endl;
  21. }
  22. else
  23. {
  24. std::cout << "Dynamic cast with pointer failed" << std::endl;
  25. }
  26.  
  27.  
  28. Base b;
  29. Base &br = b;
  30.  
  31. // throws exception if dynamic_cast is invalid
  32. try
  33. {
  34. Derived &dr = dynamic_cast<Derived&>(br);
  35. std::cout << "Dynamic cast with reference succeeded" << std::endl;
  36. }
  37. catch(std::bad_cast)
  38. {
  39. std::cout << "Dynamic cast with reference failed" << std::endl;
  40. }
  41. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
Dynamic cast with pointer failed
Dynamic cast with reference failed