Casting shared pointers in C++

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


doesn’t work with shared_ptrs. You have to use


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

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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