I'm starting to work with smart pointers in C++0X/11 and I've run into a peculiar situation. I want to up cast an instance of an object using shared_ptr.
Class Extend inherits from class Base, where Base class has a virtual destructor in order to make it polymorphic (otherwise dynamic_pointer_cast complains about non-polymorphic class casting).
if therefore:
std::shared_ptr<Base> obj = std::make_shared<Base>();
and then I do:
obj = std::dynamic_pointer_cast<Extend>(obj);
- Is it safe ?
- What happens to other pointers to the object ? Is only obj treating it as Extend, while other shared pointers will still treat it as Base?
- Is it safe to up-cast same instance or should I do something else ?
EDIT: Thank you for the answers. The real reason I was asking this question was to handle XML documents usign a SAX parser, but I got carried away with up/down casting. What I sort of wanted was:
std::shared_ptr<Extend> ex = std::dynamic_pointer_cast<Extend>(obj);
obj = ex;
But it makes no sense at all, instead I'll just use an object factory.