STL vector Problem: push_back derived object but get base object

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");}
};

main(){
vector<CBase> v;
CDerived d;
v.push_back(d);

vector<CBase>::iterator i;
for(i = v.begin(); i != v.end(); ++i){
(*i).print();
}
}
==================================

I expected it to output "Derived", however, it outputs "Base". Could anyone help me? Thank you very much.
It should work with a vector of pointers

eg:
1
2
3
4
5
6
7
8
9
    vector<CBase*> v;
    CBase *d = new CDerived;
    v.push_back(d);

   vector<CBase*>::iterator i;
   for(i = v.begin(); i != v.end(); ++i)
        (*i)->print();

   delete d;
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.

it might work if you declared the CDerived::print method as virtual....
Thanks to Bazzy and jsmith. Your advice are very helpful for me.
elvis:
>>it might work if you declared the CDerived::print method as virtual....
I tried it. It doesn't. Thanks anyway.
Of course it won't.

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.
Topic archived. No new replies allowed.