Why do we need virtual functions in C++?

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

    Virtual methods are used in interface design. For example in Windows there is an interface called IUnknown like below:

    interface IUnknown {
      virtual HRESULT QueryInterface (REFIID riid, void **ppvObject) = 0;
      virtual ULONG   AddRef () = 0;
      virtual ULONG   Release () = 0;
    };
    

    These methods are left to the interface user to implement. They are essential for the creation and destruction of certain objects that must inherit IUnknown. In this case the run-time is aware of the three methods and expects them to be implemented when it calls them. So in a sense they act as a contract between the object itself and whatever uses that object.

提交回复
热议问题