Store derived class objects in base class variables

前端 未结 5 980
一生所求
一生所求 2020-11-22 16:18

I would like to store instances of several classes in a vector. Since all classes inherit from the same base class this should be possible.

Imagine this program:

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 16:59

    What you are seeing is Object Slicing.
    You are storing object of Derived class in an vector which is supposed to store objects of Base class, this leads to Object slicing and the derived class specific members of the object being stored get sliced off, thus the object stored in the vector just acts as object of Base class.

    Solution:

    You should store pointer to object of Base class in the vector:

    vector 
    

    By storing a pointer to Base class there would be no slicing and you can achieve the desired polymorphic behavior as well.
    Since you ask for a C++ish way of doing this, the right approach is to use a suitable Smart pointer instead of storing a raw pointer in the vector. That will ensure you do not have to manually manage the memory, RAII will do that for you automatically.

提交回复
热议问题