Search code examples
c++boostshared-ptrderived-class

Boost shared_ptr passing a derived class


So I have something like so

class baseclass {
....
}

class derived : public baseclass {
...
}

void func(boost::shared_ptr<baseclass>& a){
//stuff
}

boost::shared_ptr<derived> foo;

func(foo);

Will this work? I assume not because its not the same type, however I do not posses the ability to cast it to the right type, so is there any work around that you can think of that will make this work?

Edit: the reason I can't do the cast to my knowledge is because I'm doing a sort on a vector of type boost::shared_ptr<derived>so I only call sort with vec.begin() and vec.end()


Solution

  • shared_ptr<T> can be implicitly converted to shared_ptr<U> whenever T* can be implicitly converted to U*. In particular, shared_ptr<T> is implicitly convertible to shared_ptr<T const>, to shared_ptr<U> where U is an accessible base of T, and to shared_ptr<void>.

    http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#Members

    As your code is now, though, it won't work. The implicit constuction of the boost::shared_ptr<baseclass> object must be bound to a const reference, or be copied to persist beyond construction.

    Consider either

    void func(boost::shared_ptr<baseclass> a)

    or

    void func(const boost::shared_ptr<baseclass>& a)