How to use polymorphism to access derived class vector member from base class?

后端 未结 1 522
醉话见心
醉话见心 2021-01-25 08:25

It\'s said that with polymorphism, we can access a derived class member field with it\'s base class object like this:

#include 
#include 

        
1条回答
  •  Happy的楠姐
    2021-01-25 08:59

    Runtime polymorphism in C++, achieved via virtual functions, works on covariant types. The only covariant types are pointers and references. Since you have a vector, you lose polymorphism. To retain it, store a vector. Even better, store a vector>.

    Assigning a derived class object to a base class is called object slicing. You do lose information contained in the derived object. This is the case when you are inserting a Computer into a vector.

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