Guest User

Untitled

a guest
Jan 21st, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. 1.dynamic_cast <new_type> (expression)
  2. 2.reinterpret_cast <new_type> (expression)
  3. 3.static_cast <new_type> (expression)
  4. 4.const_cast <new_type> (expression)
  5.  
  6. #include <iostream>
  7. #include <boostpolymorphic_cast.hpp>
  8.  
  9. class Base{
  10. public: virtual ~Base() = default;
  11. };
  12.  
  13. class D1 : public Base{
  14. public: virtual ~D1() = default;
  15. };
  16.  
  17. class D2 : public Base{
  18. public: virtual ~D2() = default;
  19. };
  20.  
  21.  
  22. int main(void)
  23. {
  24. D1 d1;
  25. Base* b = &d1;
  26. Base* b2 = nullptr;
  27.  
  28. std::cout << "n---Testing valid cast---n";
  29. std::cout << "cast from base to d1: " << boost::polymorphic_cast<D1*>(b) << "n";
  30.  
  31. try
  32. {
  33. std::cout << "n---Testing invalid cast---n";
  34. std::cout << "base to d2: " << boost::polymorphic_cast<D2*>(b) << "n";
  35. }
  36. catch (...)
  37. {
  38. std::cout << "cast from based to d2 failedn";
  39. }
  40.  
  41. try
  42. {
  43. std::cout << "n---Testing nullptr cast---n";
  44. std::cout << "null to d1: " << boost::polymorphic_cast<D1*>(b2) << "n";
  45. }
  46. catch (...)
  47. {
  48. std::cout << "cast from null to d1 failedn";
  49. }
  50. }
  51.  
  52. ---Testing valid cast---
  53. cast from base to d1: 00AFFBD4
  54.  
  55. ---Testing invalid cast---
  56. cast from based to d2 failed
  57.  
  58. ---Testing nullptr cast---
  59. cast from null to d1 failed
Add Comment
Please, Sign In to add comment