Why do we need virtual functions in C++?

前端 未结 26 3172
北恋
北恋 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条回答
  •  -上瘾入骨i
    2020-11-21 06:02

    i think you are referring to the fact once a method is declared virtual you don't need to use the 'virtual' keyword in overrides.

    class Base { virtual void foo(); };
    
    class Derived : Base 
    { 
      void foo(); // this is overriding Base::foo
    };
    

    If you don't use 'virtual' in Base's foo declaration then Derived's foo would just be shadowing it.

提交回复
热议问题