Exagon
Exagon

Reputation: 5088

Casting smartpointers to base class

If class B derives from class A, can I dynamic_cast a shared_ptr<B> to a shared_ptr<A>, and from shared_ptr<A> to a shared_ptr<B>?

I just ask myself because with a dynamic cast you can do something like instanceof in Java. And I asked myself if this also works for smart_ptr.

Upvotes: 2

Views: 60

Answers (1)

Alexander Kondratskiy
Alexander Kondratskiy

Reputation: 4275

For the particular case of casting from a derived class to a base class, there are assignment operators available that do the necessary implicit conversion for you. For the other direction, you can use dynamic_pointer_cast.

#include <memory>

struct A { virtual ~A() = 0; };
struct B: A { };

void example()
{
    // derived to base
    std::shared_ptr<B> b;
    std::shared_ptr<A> a = b;

    // base to derived
    std::shared_ptr<A> a2;
    std::shared_ptr<B> b2 = std::dynamic_pointer_cast<B>(a2);
}

See http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast for more info on casting operations - there are equivalents for all the usual suspects like reinterpret_pointer_cast, etc.

Upvotes: 4

Related Questions