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

前端 未结 3 1997
陌清茗
陌清茗 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:06

    The class that you are actually calling is not a class of Bar, but instead a class of Foo. What you are doing at foo_vector [0] = bar; is a call of the implicit operator= which is doing its best to make something smart happen. The memory space is still the size of a Foo though, so it can't ever be a Bar.

    0 讨论(0)
  • 2021-01-13 12:13

    When using virtual functions , you make use of pointers to objects. This way the exact function is called during run time ("How would I execute the virtual function of a derived class in the vector without knowing in advance what the derived class is?" What you mean here probably is "run time").

    The use of marking a function as virtual is that, you ask the compiler to postpone or figure out the "TYPE" of an object calling that function at run time rather than the usual way "compile time" . This is achieved by using pointers to objects. So to put it in a simple line "Use pointers to objects to make use of Virtual functions".

    0 讨论(0)
  • 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.

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