Search code examples
c++pure-virtual

C++ pure virtual function have body


Pure virtual functions (when we set = 0) can also have a function body.

What is the use to provide a function body for pure virtual functions, if they are not going to be called at all?


Solution

  • Your assumption that pure virtual function cannot be called is absolutely incorrect. When a function is declared pure virtual, it simply means that this function cannot get called dynamically, through a virtual dispatch mechanism. Yet, this very same function can easily be called statically, non-virtually, directly (without virtual dispatch).

    In C++ language a non-virtual call to a virtual function is performed when a qualified name of the function is used in the call, i.e. when the function name specified in the call has the <class name>::<function name> form.

    For example

    struct S 
    {
      virtual void foo() = 0;
    };
    
    void S::foo() 
    {
      // body for pure virtual function `S::foo`
    }
    
    struct D : S 
    {
      void foo() 
      {
        S::foo();       
        // Non-virtual call to `S::foo` from derived class
    
        this->S::foo(); 
        // Alternative syntax to perform the same non-virtual call 
        // to `S::foo` from derived class
      }
    };
    
    int main() 
    {
      D d;
    
      d.S::foo(); 
      // Another non-virtual call to `S::foo`
    }