
Hello R.P, Inheriting from enable_shared_from_this more than once is not a good idea.
From: boost-users-bounces@lists.boost.org [mailto:boost-users- bounces@lists.boost.org] On Behalf Of R. P. Janaka Sent: Monday, August 10, 2009 6:54 AM To: boost-users@lists.boost.org Subject: Re: [Boost-users] How shared_from_this() work when it inherited from more than one time
But in my case there is no option like this (Class A is a base library class). So I have to do this.
Don't let B inherit from enable_shared_from_this. You've already done that in A. So your question then becomes "how do I retrieve a shared_ptr<B> from this?". Here's how: boost::shared_dynamic_cast(shared_from_this()); In the example you've provided, it would also be safe to use boost::shared_static_cast. To conclude: You should only inherit from enable_shared_from_this in A, and B should only inherit from A.
I did the above to avoid the ambiguous call error So how can I specify that i am calling the shared_from_this() in class B....?
You did. But the problem is that you have two weak_ptrs -- one weak_ptr<A> and one weak_ptr<B> -- and only one of them will be initialized correctly when you create the smart pointer. (If you're interested in debugging your case to really understand what happens, have a look at the function sp_enable_shared_from_this() in shared_ptr.hpp.) Does that help? Cheers, Bjorn Karlsson