boost::shared_ptr and dynamic cast

HolyLa picture HolyLa · Nov 25, 2010 · Viewed 32.2k times · Source

I have a problem using a shared_ptr of a base class, I can't seem to be able to call the derived class's methods when dereferencing it. I believe code will be more verbose than me:

class Base : public boost::enable_shared_from_this<Base>
{
  public:
    typedef  boost::shared_ptr<BabelNet> pointer;
};

class Derived : public Base
{
  public:
     static pointer  create()
                {
                        return pointer(new Derived);
                }
     void             anyMethod()
     {
        Base::pointer foo = Derived::create();
        // I can't call any method of Derived with foo
        // How can I manage to do this ?
        // is dynamic_cast a valid answer ?
        foo->derivedMethod(); // -> compilation fail
     }

};

Answer

lijie picture lijie · Nov 25, 2010

see static_cast with boost::shared_ptr?

you'll need to use dynamic_pointer_cast to get the appropriate shared_ptr instantiation. (corresponding to a dynamic_cast)