C ++: can a <Base> vector contain objects of type Derived?

The name says a lot about everything. Basically, this is legal for this:

class Base {
    //stuff
}

class Derived: public Base {
    //more stuff
}

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

Based on the other posts I saw, everything is fine, but I do not want to use pointers in this case, because it is more difficult to make it thread safe.

vector<Base*> foo;
Derived* bar = new Derived;
foo.push_back(bar);
+5
source share
3 answers

No, objects Derivedwill be sliced : all additional members will be dropped.

Use instead of source pointers std::vector<std::unique_ptr<Base> >.

+13
source

, . , Base. , ... Base .

.

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

, push_back :

void push_back ( const T& x );

Thus, the compiler will do an implicit down conversion and copy to the vector memory pool. No, inside is vector<Base>impossible to contain Derived. They will be Base.

If you add some virtual function to Base, then override it in Derived, create an object Derived, paste it in vector<Base>and then call it from a new vector object, you will see that the implementation Baseis called

0
source

All Articles