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

后端 未结 1 508
醉话见心
醉话见心 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条回答
  • 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<Tool>, you lose polymorphism. To retain it, store a vector<Tool*>. Even better, store a vector<unique_ptr<Tool>>.

    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<Tool>.

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