A.Saroj
A.Saroj

Reputation: 61

What is the use of dynamic_pointer_cast in C++? When is it used? What are alternatives for dynamic_pointer_cast?

I was reading about dynamic_pointer_cast.

I found that we can dynamically upcast or downcast the shared pointer of one type to another at run time but

I didn't understand the concept completely.

Shall both the classes must have same properties?

If the properties must be same then what is need of dynamic casting?

Upvotes: 6

Views: 10188

Answers (1)

Fedor
Fedor

Reputation: 21089

dynamic_pointer_cast is used to convert std::shared_ptr type, e.g. from the pointer on a base class to a pointer on a derived class:

#include <memory>

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

int main()
{
    std::shared_ptr<A> pA = std::make_shared<B>();
    std::shared_ptr<B> pB = std::dynamic_pointer_cast<B>(pA);
}

So dynamic_pointer_cast is a convenience wrapper around dynamic_cast:

template< class T, class U > 
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{
    if (auto p = dynamic_cast<typename std::shared_ptr<T>::element_type*>(r.get())) {
        return std::shared_ptr<T>{r, p};
    } else {
        return std::shared_ptr<T>{};
    }
}

Upvotes: 12

Related Questions