I'm going to use downcasting in my project in order to cast one boost::shared_ptr<> to another one in class hierarchy. That is my test code where I am using boost/polymorphic_pointer_cast and boost::dynamic_pointer_cast both variant work. But I don't understand what is difference between them. Could you describe me what is difference between boost::polymorphic_pointer_downcast
and boost::dynamic_pointer_cast
?
namespace cast
{
class Base
{
public:
virtual void kind() { std::cout << "base" << std::endl; }
};
class Derived : public Base
{
public:
virtual void kind2() { std::cout << "derived" << std::endl; }
};
}
int main(int argc, char* argv[])
{
try
{
boost::shared_ptr<cast::Base> base(new cast::Derived());
base->kind();
boost::shared_ptr<cast::Derived> d1 = boost::polymorphic_pointer_downcast<cast::Derived>(base);
d1->kind();
d1->kind2();
boost::shared_ptr<cast::Derived> d2 = boost::dynamic_pointer_cast<cast::Derived>(base);
d2->kind();
d2->kind2();
}
catch (const std::exception& e)
{
std::cerr << "Error occurred: " << e.what() << std::endl;
}
return 0;
}
Thanks.