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

浪尽此生 提交于 2019-11-27 02:10:33
ecatmur

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!