Dan Bloomquist wrote:
Gavin Deane wrote:
Naren wrote:
>Hi,
why cant a list<derived*be implicitly castable to list<base*>?
http://www.parashift.com/c++-faq-lit....html#faq-21.3
I'm not following here. The containers are of pointers, not objects. (I
assume the objects are created on the heap.)
The containers have to be of pointers not objects otherwise there is no
polymorphism involved at all and the question can't even arise.
How would this be wrong?:
<snip code that contains a dynamic cast from base* to derived*>
Your example is not what the OP, or the FAQ I pointed to, is talking
about.
The OP wants to be able to convert implicitly from a list<derived*to
a list<base*>. The point in the FAQ is that, if Fruit is the base class
and Apple and Orange are two classes derived from Fruit, converting a
container of Apples to a container of Fruit would allow you to put an
Orange in the container of Apples. Implicit in that is that the
containers hold pointers, not objects. It is only possible to have the
concept of a container of Fruit holding Apples if the stored type is a
pointer. The OP's question was about containers of pointers.
#include <list>
using std::list;
class base { /* ... */ };
class derived1 : public base { /* ... */ };
class derived2 : public base { /* ... */ };
void f(list<base*>& bl)
{
// This is OK. derived1 and derived2 both derive
// from base so both can be pointed to by a base*
bl.push_back(new derived1);
bl.push_back(new derived2);
}
int main()
{
list<base*base_list;
f(base_list);
// base_list now contains two pointers. The first
// points to a derived1, the second points to a
// derived2.
// The first push_back is OK
// The second won't compile because d1_list
// is a list of derived1* not a list of derived2*
list<derived1*d1_list;
d1_list.push_back(new derived1);
d1_list.push_back(new derived2);
list<derived1*another_d1_list;
// The OP wants to be able to do this somehow
f(another_d1_list);
// If the above were possible, what should happen
// when function f tries to put a derived2* in
// this list of derived1*? That would be
// equivalent to the statement above that quite
// sensibly does not compile.
}
Also have a look at the rest of FAQ 21.
Gavin Deane