18_casts.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <iostream>
  2. using namespace std;
  3. class Base
  4. {
  5. virtual void dummy()
  6. {
  7. // Required to make class polymorphic
  8. }
  9. // Some base class
  10. };
  11. class Derived : public Base
  12. {
  13. // Some derived class
  14. };
  15. int main()
  16. {
  17. Base *base = new Base;
  18. Base *derived = new Derived;
  19. Derived *tmp;
  20. tmp = dynamic_cast<Derived *>(base);
  21. if (tmp)
  22. cout << "Base* has been successfully casted to Derived* using dynamic_cast"
  23. << endl;
  24. else
  25. cout << "dynamic_cast prevented Base* cast to Derived* from happening"
  26. << endl;
  27. tmp = dynamic_cast<Derived *>(derived);
  28. if (tmp)
  29. cout << "Derived* has been successfully casted to Derived* using "
  30. "dynamic_cast"
  31. << endl;
  32. else
  33. cout << "dynamic_cast prevented Derived* cast to Derived* from happening"
  34. << endl;
  35. tmp = static_cast<Derived *>(base);
  36. if (tmp)
  37. cout << "Base* has been successfully casted to Derived* using static_cast"
  38. << endl;
  39. else
  40. cout << "This actually never happens" << endl;
  41. tmp = static_cast<Derived *>(derived);
  42. if (tmp)
  43. cout
  44. << "Derived* has been successfully casted to Derived* using static_cast"
  45. << endl;
  46. else
  47. cout << "This actually never happens" << endl;
  48. return 0;
  49. }