Polymorphism and vectors
chris jefferson
caj@cs.york.ac.uk
Mon Jul 11 11:18:00 GMT 2005
Anakreon wrote:
> I have a little problem with polymorphism and vectors.
>
This mailing list is for the development OF libstdc++, not WITH, so you
shouldn't really be mailing here unless you think you've found a bug in
the library. gcc-help (or a newsgroup, such as comp.lang.c++) would be
more approriate. However, I'll answer your question anyway :)
>------------------------------------------------------------------------
>
>...
>
> vector<base*> vect;
> ...
> for (vector<base*>::iterator it = vect.begin();
> it != vect.end(); it++) {
> cout << typeid(*it).name() << endl;
> }
>
>
>
Here you are asking for the type of a pointer to base, and so thats what
you get!
If you want the type of the thing the pointer points to, you have to do
typeid(**it).name(), which then gets you what you would expect. This is
broadly the right way to do what you are trying to do (although
getting one of the various reference-counted pointers will make your
life much easier in terms of not having to manually delete things as and
when you eject them from the vector).
>...
> vector<base> v2;
>
>
>...
> for (vector<base>::iterator it = v2.begin();
> it != v2.end(); it++) {
> cout << typeid(*it).name() << endl;
> }
>
>
Here you have a problem with something known as slicing. Basically the
vector will convert all the objects to bases when they are inserted, by
ignoring the non-base part. This is bad! :)
Chris
More information about the Libstdc++
mailing list