This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Polymorphism and vectors


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]