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
}
};
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
)
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.
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.
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.
精彩评论