#include 'iostream' class A { private: int a; public : A(): a(-1) {} int getA() { return a; } }; class A; class B : public A { private: int b; public: B() : b(-1) {} int getB() { return b; } }; int main() { std::auto_ptr<A> a = new A(); std::auto_ptr<B> b = dynamic_cast<std::auto_ptr<B> > (a); return 0; }
ERROR: cannot dynamic_cast `(&a)->std::auto_ptr<_Tp>::get() const
Well,
std::auto_ptr<B>is not derived fromstd::auto_ptr<A>. ButBis derived fromA. The auto_ptr does not know about that (it’s not that clever). Looks like you want to use a shared ownership pointer.boost::shared_ptris ideal, it also provides a dynamic_pointer_cast:For auto_ptr, such a thing can’t really work. Because ownership will move to
b. But if the cast fails, b can’t get ownership. It’s not clear what to do then to me. You would probably have to say if the cast fails, a will keep having the ownership – which sounds like it will cause serious trouble. Best start using shared_ptr. Bothaandbthen would point to the same object – butBas ashared_ptr<B>andaas ashared_ptr<A>