Thank you for you time to answer. Allthough your answer has helped me, I still have the bad_weak_ptr exception. Every time I try to access the shared_from_this pointer from inside Base member functions, I get that exception. What I want to know is how can I access safely an without errors, the shared_from_this pointer inside my Base class, when I create a smart pointer instance of my Derived class.

In derived I don't have that problem  (I can access shared_from_this) because this is the class the instance is created.

Thanks in advance
 
Peter Dimov wrote:
Yaoltzin Gomez wrote:

> Basically, what I have is this:
>
> class Base : public boost::enable_shared_from_this<Base>
> {
>    boost::shared_ptr<Base> GetBasePointer()
>    {
>       return shared_from_this();
>    }
>
>    void Foo()
>    {
>       shared_ptr<Child> child( new Child );
>       AddChild( child, GetBasePointer() );
>    }
> };
>
> class Derived: public Base, public
> boost::enable_shared_from_this<Derived> {
>    boost::shared_ptr<Derived> GetDerivedPointer()
>    {
>       return shared_from_this();
>    }

[...]

One way to avoid putting more than one enable_shared_from_this<> base into
Derived is to use

class Derived: public Base
{
    boost::shared_ptr<Derived> GetDerivedPointer()
    {
       return dynamic_pointer_cast<Derived>( shared_from_this() );
    }

    // ...
};

static_pointer_cast will also work in this case (it will fail if Derived
uses virtual inheritance).