Convert Base class weak_ptr to child class shared_ptr

Viewed 31

I have below code snipped

#include<bits/stdc++.h>
using namespace std;
class A{
    public:
       A(){}
};
class B : public A{
    public:
        B(){}
};
int main() {
   shared_ptr<B> bb = make_shared<B>();
   weak_ptr<A> aa = bb;
   shared_ptr<A> cc = aa.lock();
   if(cc){
      shared_ptr<B> bbc = dynamic_pointer_cast<B>(cc);// giving error
   }
}

How can I convert the base class weak_ptr to derived class shared_ptr ? I tried using dynamic_pointer_cast but that is giving me an error.

In file included from prog_joined.cpp:1:
In file included from ./precompiled/headers.h:51:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/memory:81:
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/shared_ptr.h:510:23: error: 'A' is not polymorphic
      if (auto* __p = dynamic_cast<typename _Sp::element_type*>(__r.get()))
                      ^                                         ~~~~~~~~~
Line 16: Char 27: note: in instantiation of function template specialization 'std::dynamic_pointer_cast<B, A>' requested here
      shared_ptr<B> bbc = dynamic_pointer_cast<B>(cc);
0 Answers
Related