6

Boost smart pointers can be used with polymorphism, but how do you cast the subclass back to the pointer?

using namespace boost;
// ...
shared_ptr<SuperClass> a_ptr(new SubClass);
// ...
shared_ptr<SubClass> b_ptr = (shared_ptr<SubClass>)a_ptr; // Doesn't compile

The last line doesn't compile and gives error C2440: 'type cast' : cannot convert from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'

Community
  • 1
  • 1
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

1 Answers1

12

You need to use static_pointer_cast:

struct B { virtual ~B() { } };
struct D : B { };

shared_ptr<B> bp(new D);
shared_ptr<D> dp(static_pointer_cast<D>(b));

(There are also dynamic_pointer_cast and const_pointer_cast for performing dynamic and const casts respectively.)

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • I think that should be `dynamic_pointer_cast` in this case, right? – Philipp Jan 21 '11 at 22:43
  • If it is unknown at compile time if the type is the one specified in the <> that is. Else boost::static_pointer_cast should be used. – Marius K Aug 16 '12 at 14:11