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
}
};
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.
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).
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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With