Search code examples
c++c++11polymorphismshared-ptr

C++: saving derived class in shared_ptr of base class


I want to have a class that has a shared pointer as member:

class MyClass {
public:
    shared_ptr<MyAbstractBaseClass> myPointer;
}

How can I make the pointer point to an instance of a derived class?


Solution

  • If the question is about assigning a plain derived pointer, all you have to do is:

    struct B { };
    struct D : B { }; 
    
    D *pd = new D; 
    shared_ptr<B> sp(pd); 
    

    If the question is to convert a shared_ptr to a derived to shared_ptr to a base class, you can do this:

    shared_ptr<D> spd = make_shared<D>(); 
    shared_ptr<B> sp = static_pointer_cast<B>(spd);