dynamic_cast across a shared_ptr?

mezamorphic picture mezamorphic · May 22, 2014 · Viewed 23.1k times · Source

I have two classes A and B, B inherits from A.

If I have a shared_ptr<A> object which I know is really a B subtype, how can I perform a dynamic cast to access the API of B (bearing in mind my object is shared_ptr, not just A?

Answer

Dietmar K&#252;hl picture Dietmar Kühl · May 22, 2014

If you just want to call a function from B you can use one of these:

std::shared_ptr<A> ap = ...;
dynamic_cast<B&>(*ap).b_function();
if (B* bp = dynamic_cast<B*>(ap.get()) {
    ...
}

In case you actually want to get a std::shared_ptr<B> from the std::shared_ptr<A>, you can use use

std::shared_ptr<B> bp = std::dynamic_pointer_cast<B>(ap);