Search code examples
c++inheritanceshared-ptr

How to cast a shared_ptr<A> to shared_ptr<B> where B is derived from A?


I have a std::list container, holding shared pointers of say class A. I have another class, say B, that is derived from A.

I currently have code that does this to populate the container:

shared_ptr<B> b = shared_ptr<B>(new B);
container.push_back(b)

This works fine.

Question is, how can I retrieve the shared_ptr < B > that was initially pushed back to the container?

Doing the following

   list<shared_ptr<A> >::iter anIter = myContainer.begin();
   shared_ptr<B> aB = *(anIter);

do not compile. I get error

Cannot convert 'A * const' to 'B *'

Any tips?


Solution

  • You can use std::dynamic_pointer_cast.

    You use it like this:

    std::shared_ptr<Base> basePtr;
    std::shared_ptr<Derived> derivedPtr = std::dynamic_pointer_cast<Derived>(basePtr);