HolyLa
HolyLa

Reputation: 153

boost::shared_ptr and dynamic cast

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
     }

};

Upvotes: 15

Views: 34648

Answers (4)

lijie
lijie

Reputation: 4871

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)

Upvotes: 19

icecrime
icecrime

Reputation: 76745

Shared pointer or not, when you have a pointer to a Base, you can only call member functions from Base.

If you really need to dynamic_cast, you can use dynamic_pointer_cast from boost, but chances are that you shouldn't. Instead, think about your design : Derived is a Base, and this is an extremely strong relationship, so think carefully about Base interface and if the concrete type really has to be known.

Upvotes: 4

Simone
Simone

Reputation: 11797

Your code wouldn't work even with raw pointers.

You need either to declare derivedMethod() method even in base class or to have a pointer to aDerived object.

Upvotes: 0

Cătălin Pitiș
Cătălin Pitiș

Reputation: 14341

If derivedMethod is not declared in base class (virtual or not), then it is normal that the compilation would fail. The shared ptr knows and uses the base class (through the pointer it holds), and knows nothing about the derived class and its specific methods.

Upvotes: 1

Related Questions