Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
     }

};
like image 759
HolyLa Avatar asked Nov 25 '10 13:11

HolyLa


People also ask

What is the difference between static and dynamic cast?

static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.

What is a dynamic cast in C++?

In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference). It can also be used for upcasting; i.e., casting a derived class pointer (or reference) to a base class pointer (or reference).

What is the use of dynamic cast operator?

The dynamic_cast operator ensures that if you convert a pointer to class A to a pointer to class B , the object of type A pointed to by the former belongs to an object of type B or a class derived from B as a base class subobject.

What is dynamic pointer cast?

A pointer (or reference) to a class can actually point (refer) to any class derived from that class. Occasionally, it may be desirable to obtain a pointer to the fully derived class, or to some other subobject of the complete object. The dynamic cast provides this facility.


1 Answers

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)

like image 148
lijie Avatar answered Sep 21 '22 14:09

lijie