Why do we need virtual functions in C++?

前端 未结 26 3128
北恋
北恋 2020-11-21 05:50

I\'m learning C++ and I\'m just getting into virtual functions.

From what I\'ve read (in the book and online), virtual functions are functions in the base class that

26条回答
  •  别那么骄傲
    2020-11-21 06:25

    When you have a function in the base class, you can Redefine or Override it in the derived class.

    Redefining a method : A new implementation for the method of base class is given in the derived class. Does not facilitate Dynamic binding.

    Overriding a method: Redefining a virtual method of the base class in the derived class. Virtual method facilitates Dynamic Binding.

    So when you said :

    But earlier in the book, when learning about basic inheritance, I was able to override base methods in derived classes without using 'virtual'.

    you were not overriding it as the method in the base class was not virtual, rather you were redefining it

提交回复
热议问题