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


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


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