xgb84j
xgb84j

Reputation: 561

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?

Upvotes: 0

Views: 706

Answers (1)

Christophe
Christophe

Reputation: 73446

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); 

Upvotes: 2

Related Questions