I would like to store instances of several classes in a vector. Since all classes inherit from the same base class this should be possible.
Imagine this program:
#include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
virtual void identify ()
{
cout << "BASE" << endl;
}
};
class Derived: public Base
{
public:
virtual void identify ()
{
cout << "DERIVED" << endl;
}
};
int main ()
{
Derived derived;
vector<Base> vect;
vect.push_back(derived);
vect[0].identify();
return 0;
}
I expected it to print "DERIVED", because the "identify" method is virtual. Instead 'vect[0]' seems to be a 'Base' instance and it prints
BASE
I guess I could write my own container (probably derived from vector) somehow that is capable of doing this (maybe holding only pointers...). I just wanted to ask if there is a more C++ish method for doing this. AND I would like to be completely vector-compatible (just for convenience if other users should ever use my code).
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…