Why do we need virtual functions in C++?

前端 未结 26 3133
北恋
北恋 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:07

    Virtual Functions are used to support Runtime Polymorphism.

    That is, virtual keyword tells the compiler not to make the decision (of function binding) at compile time, rather postpone it for runtime".

    • You can make a function virtual by preceding the keyword virtual in its base class declaration. For example,

       class Base
       {
          virtual void func();
       }
      
    • When a Base Class has a virtual member function, any class that inherits from the Base Class can redefine the function with exactly the same prototype i.e. only functionality can be redefined, not the interface of the function.

       class Derive : public Base
       {
          void func();
       }
      
    • A Base class pointer can be used to point to Base class object as well as a Derived class object.

    • When the virtual function is called by using a Base class pointer, the compiler decides at run-time which version of the function - i.e. the Base class version or the overridden Derived class version - is to be called. This is called Runtime Polymorphism.

提交回复
热议问题