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


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 :)
I didn't know about the comp.lang.c++ list. I knew that the question was not
apropriate for this list but had to ask. Sorry about this. I'll post to the right list
next time.
 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).


Ah, I see. This works perfectly. Thanks.
...
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! :)
Actually I knew about this. I placed the code in order to see if any difference would
exist in the output generated by the two loops.


Thanks Chris.


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