This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: Polymorphism and vectors
- From: Jonathan Wakely <cow at compsoc dot man dot ac dot uk>
- To: Anakreon <anakreonmejdi at yahoo dot gr>
- Cc: libstdc++ at gcc dot gnu dot org
- Date: Mon, 11 Jul 2005 11:56:14 +0100
- Subject: Re: Polymorphism and vectors
- References: <datiak$19p$1@sea.gmane.org>
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