Pergunta

The title pretty much says it all. Basically, is it legal to do this:

class Base {
    //stuff
}

class Derived: public Base {
    //more stuff
}

vector<Base> foo;
Derived bar;
foo.push_back(bar);

Based on other posts I've seen, the following is okay, but I don't want to use pointers in this case because it's harder to make it thread safe.

vector<Base*> foo;
Derived* bar = new Derived;
foo.push_back(bar);
Foi útil?

Solução

No, the Derived objects will be sliced: all additional members will be discarded.

Instead of raw pointers, use std::vector<std::unique_ptr<Base> >.

Outras dicas

It's legal but suffers from object slicing. Basically, you'll have a vector of Base objects. No polymorphism, type info will be lost for derived objects... It's as if you'd just be adding Base objects to the vector.

You can use smart pointers instead.

vector<Base> foo;
Derived bar;
foo.push_back(bar);

This is equal to pushing Base object, because push_back is declared like this:

void push_back ( const T& x );

So, compiler will do implicit downgrading conversion and do copy into vector memory pool. No, it is not possible to contain Derived inside vector<Base>. They will be Base.

If you add some virtual function to Base then override it in Derived, create Derived object, push it into vector<Base> and then call it from vector's new object, you will see that Base implementation is called

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top