Search code examples
c++functionpure-virtual

Difference between a virtual function and a pure virtual function


What is the difference between a pure virtual function and a virtual function?

I know "Pure Virtual Function is a Virtual function with no body", but what does this mean and what is actually done by the line below:

virtual void virtualfunctioname() = 0

Solution

  • A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:

     Derived d;
     Base& rb = d;
     // if Base::f() is virtual and Derived overrides it, Derived::f() will be called
     rb.f();  
    

    A pure virtual function is a virtual function whose declaration ends in =0:

    class Base {
      // ...
      virtual void f() = 0;
      // ...
    

    A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.

    An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation. (What that's good for is debatable.)


    Note that C++11 brought a new use for the delete and default keywords which looks similar to the syntax of pure virtual functions:

    my_class(my_class const &) = delete;
    my_class& operator=(const my_class&) = default;
    

    See this question and this one for more info on this use of delete and default.