2

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

csteifel
  • 2,854
  • 6
  • 35
  • 61

3 Answers3

4

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)

Tarc
  • 3,214
  • 3
  • 29
  • 41
Steven Maitlall
  • 777
  • 3
  • 5
1

Yes, it will work. Wouldn't it have been quicker just to compile it than to ask here?

shared_ptr has a templated converting constructor that allows implicit conversions from shared_ptr<D> to shared_ptr<B> if (and only if) D* is implicitly convertible to B*

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
1

I'd be very much surprised. You need to pass lvalue of the proper type. For that to work the class should be base class and it is not the case.

NOTE: If if your function would take the ptr by value or const& other rules would apply.

Balog Pal
  • 16,195
  • 2
  • 23
  • 37