Casting shared pointers in C++

Here’s a note on my experience with casting a base class shared pointer to a derived class pointer.

dynamic_cast<derived_class*>(base_class) 

doesn’t work with shared_ptrs. You have to use

dynamic_pointer_cast<derived_class>(base_class)

Another example below,

#include <iostream>
#include <memory>
 
struct BaseClass {};
 
struct DerivedClass : BaseClass
{
    void f() const
    {
        std::cout << "Hello World!\n";
    }
};
 
int main()
{
    std::shared_ptr<BaseClass> ptr_to_base(std::make_shared<DerivedClass>());
 
    // ptr_to_base->f(); // Error won't compile: BaseClass has no member named 'f'
 
    std::static_pointer_cast<DerivedClass>(ptr_to_base)->f(); // OK
    // (constructs a temporary shared_ptr, then calls operator->)
 
    static_cast<DerivedClass*>(ptr_to_base.get())->f(); // also OK
    // (direct cast, does not construct a temporary shared_ptr)
}

We can either cast the shared pointer directly by setting the type to the DerivedClass, or just use the raw points with “.get()” and static_cast in the second approach (direct cast).

Reference Materials

https://doc.bccnsoft.com/docs/cppreference2015/en/cpp/memory/shared_ptr/pointer_cast.html

https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s