Advertisement
andrejpodzimek

Type cast failures in C++: pointers vs references

Aug 3rd, 2022
939
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <iostream>
  2. #include <memory>
  3. #include <typeinfo>
  4. #include <vector>
  5.  
  6. namespace {
  7.   using std::bad_cast;
  8.   using std::cout;
  9.   using std::make_unique;
  10.   using std::unique_ptr;
  11.   using std::vector;
  12.  
  13.   struct B { virtual void method() const = 0; virtual ~B() = default; };
  14.   struct D1 : public B { void method() const override { cout << "D1\n"; } };
  15.   struct D2 : public B { void method() const override { cout << "D2\n"; } };
  16. }
  17.  
  18. int main() {
  19.   const vector<unique_ptr<B>> objects{[] {
  20.     vector<unique_ptr<B>> objects;
  21.     objects.reserve(2);
  22.     objects.push_back(make_unique<D2>());
  23.     objects.push_back(make_unique<D1>());
  24.     return objects;
  25.   }()};
  26.   for (const auto& object_ptr : objects) {
  27.     if (const auto *const ptr{dynamic_cast<D1*>(object_ptr.get())}; ptr) {
  28.       cout << "Successfully cast pointer to D1*; calling method(): ";
  29.       ptr->method();
  30.     } else {
  31.       cout << "Failed to cast pointer to D1*; calling method(): ";
  32.       object_ptr->method();
  33.     }
  34.     try {
  35.       const auto &ref{dynamic_cast<D1&>(*object_ptr)};
  36.       cout << "Successfully cast reference to D1&; calling method(): ";
  37.       ref.method();
  38.     } catch (const bad_cast&) {
  39.       cout << "Failed to cast reference to D1&; calling method(): ";
  40.       object_ptr->method();
  41.     }
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement