C++: Calling the virtual function of the derived class

前端 未结 3 1998
陌清茗
陌清茗 2021-01-13 11:41

Suppose I have a class with a virtual function and a derived class that implements the virtual function in a different way. Suppose I also have a vector of the base class u

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 12:16

    You can't. The objects in the vector will have been sliced -- any derived-class instance data will have been chopped off, so calling the method would be a super-bad idea.

    If, on the other hand, you have a vector of pointers to base, then you simply call the virtual method, and the derived-class version will be invoked.

提交回复
热议问题