Polymorphism and vectors
Jonathan Wakely
cow@compsoc.man.ac.uk
Mon Jul 11 10:56:00 GMT 2005
On Mon, Jul 11, 2005 at 01:34:10PM +0300, Anakreon wrote:
> I have a little problem with polymorphism and vectors.
This problem is nothing to do with libstdc++ development, it is a basic
C++ question so is not approrpiate on this mailing list.
> Consider the example in the attached file
>
> The output of the program is:
> 4base, 2b1, 2b2, 2b3
> P4base
> P4base
> P4base
>
> 4base
> 4base
> 4base
>
> Why are the descendants of class "base" are returned as instances of class
> "base"?
Because you're slicing the objects when you insert them into the vector.
I suggest you read this FAQ:
http://parashift.com/c++-faq-lite/containers.html#faq-34.4
> Is there a solution to this problem?
Don't store polymorphic objects in containers by value, store a (smart)
pointer. Alternatively, use something like the new Boost.PtrContainers
library.
jon
--
"A woman drove me to drink, I never had the courtesy to thank her."
- W.C. Fields
More information about the Libstdc++
mailing list