Re: Problem with static downcast of base type to derived type
On Jul 2, 2:29 pm, Dom Jackson <nos...@mci2000.com> wrote:
Thanks folks - I had no idea that you couldn't put a derived type in a
set of base types. I can't immediately see anything in Josuttis about
this. Can anyone tell me what the problem is here?
One practical problem is that in general a derived object may not fit
in space for a base object.
Is this common to
all STL containers?
It is not specific to containers; "slicing" can be demonstrated even
with this code:
Derived d;
Base b = d;
What happens is that the Base part of d is copied to b. The same thing
happens when you copy Derived objects into a vector<Base>.
I had rather naively assumed that an object of a
derived type actually was, to all intents and purposes, also a base
object, but that's obviously not the case.
That is all true. As long as the object maintains its own identity. As
soon as you copy it to Base, it is sliced to its Base part.
In order to have a collection of polymorpic objects, you must use a
type that would prevent slicing the objects. These all work fine:
boost::ptr_vector<Base> v0;
vector<boost::shared_ptr<Base> > v0;
This works too, but not exception safe:
vector<Base *> v1;
Ali