This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Polymorphism and vectors
- From: Anakreon <anakreonmejdi at yahoo dot gr>
- To: libstdc++ at gcc dot gnu dot org
- Date: Mon, 11 Jul 2005 13:34:10 +0300
- Subject: Polymorphism and vectors
I have a little problem with polymorphism and vectors.
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"?
Is there a solution to this problem?
Thanks is advance,
Anakreon
#include <vector>
#include <iostream>
#include <typeinfo>
using namespace std;
class base {
public:
virtual ~base() {}
};
class b1 : public base {};
class b2 : public base {};
class b3 : public base {};
int main() {
cout << typeid(base).name() << ", "
<< typeid(b1).name() << ", "
<< typeid(b2).name() << ", "
<< typeid(b3).name() << endl;
vector<base*> vect;
vect.push_back(new b1);
vect.push_back(new b2);
vect.push_back(new b3);
for (vector<base*>::iterator it = vect.begin();
it != vect.end(); it++) {
cout << typeid(*it).name() << endl;
}
cout << endl;
vector<base> v2;
v2.push_back(b1());
v2.push_back(b2());
v2.push_back(b3());
for (vector<base>::iterator it = v2.begin();
it != v2.end(); it++) {
cout << typeid(*it).name() << endl;
}
}