STL container to hold Child objects +! pointers – slicing — but slicing problem!

struct Base {
    virtual void print() const{cout<<1<<"\n";}
    virtual ~Base(){}
struct Derived : public Base {
    virtual void print() const{cout<<2<<"\n";}
int main(){
    Base b;
    Derived d;
    std::vector v;
    v.push_back(b); // OK
    v.push_back(d); // no error but not sure if there’s any hidden issue
    cout<<  v.size() <<endl; // prints 2
    std::vector::const_iterator pos;
    for(pos = v.begin(); pos != v.end(); ++pos){
       pos->print(); // Der object sliced!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s