Hello, I have a problem about STL vector. I expect vector can hold my derived objects. But it doesn't. My program is like this:
==================================
#include <vector>
using namespace std;
class CBase{
public:
virtual void print(){ printf("Base\n");}
};
class CDerived : public CBase{
public:
void print(){ printf("Derived\n");}
};
STL containers do not support polymorphism, so your only option is to store pointers as Bazzy suggested. However, if you are going to go that far, consider using boost::ptr_vector instead which takes ownership of the pointer when inserted and automatically destroys the pointer for you when removed.
The declaration vector<CBase> allocates memory to store objects of type CBase. The compiler has to know sizeof( CBase ) in order to allocate the right amount of memory. Derived classes add to the size. If you try to insert a derived class into a vector of base class objects, what happens is the object gets spliced and literally becomes a base class instance.