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

后端 未结 3 895
轻奢々
轻奢々 2020-11-29 11:46

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

class Base {
    //stuff
}

class Derived: public Base {
    //more stuff
}

vector<         


        
相关标签:
3条回答
  • 2020-11-29 11:54

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

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

    0 讨论(0)
  • 2020-11-29 12:14

    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.

    0 讨论(0)
  • 2020-11-29 12:17
    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

    0 讨论(0)
提交回复
热议问题