As with all templates, a class<A> is not related to a class<B>, no matter whether A and B are related or not.
However, you could write:
Code:
auto_ptr<B> ptr(new D);
and that would be fine.
Note, however, that the D object will be destroyed after the call to bar() since you're passing the auto_ptr by value. This is unintuitive, which is why auto_ptr has been deprecated in favor of unique_ptr, which has the same behavior but is explicitly only movable, not copyable.
As with all templates, a class<A> is not related to a class<B>, no matter whether A and B are related or not.
But if you write your own template class you can make class<A> convertible to class<B> by providing an overloaded constructor, as is done for shared_ptr.
shared_ptr<T> can be implicitly converted to shared_ptr<U> whenever T* can be implicitly converted to U*. In particular, shared_ptr<T> is implicitly convertible to shared_ptr<T const>, to shared_ptr<U> where U is an accessible base of T, and to shared_ptr<void>.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
But if you write your own template class you can make class<A> convertible to class<B> by providing an overloaded constructor, as is done for shared_ptr.
in principle auto_ptr can convert from/to auto_ptr's whose base pointers are convertible;
the problem in the OP code is that auto_ptr exposes both a template copy ctor taking any auto_ptr<T> by non const reference and a template conversion operator to any auto_ptr<T> which give an ambiguous overload resolution error in the bar argument copy-initialization. As in
Code:
struct A;
struct B { B( A& ); }; // if it were "B( const A& );" it would compile
struct A { operator B(); };
void bar( B );
int main()
{
A a;
bar(a);
}
indeed, an alternative to "auto_ptr<B> ptr = auto_ptr<B>( new D() )" is
Code:
int main()
{
auto_ptr<D> ptr(new D);
bar( auto_ptr<B>(ptr) );
}
Bookmarks