A pure virtual function is a special type of virtual function where we do not defined the function body and a derived class has to define the body.

For example:

#include <iostream>
 
class Base
{
public:
    virtual void msg() const = 0;
};
 
class Derived : public Base
{
public:
    void msg() const override
    {
        std::cout << "Derived msg" << '\n';
    }
};
 
int main(int argc, char const *argv[])
{
    // Base b; // doesn't work as it is an abstract class
 
    Derived d;
    d.msg();
 
    return 0;
}

Here, we have made Base::msg() as pure virtual function using = 0 syntax. This makes Base class an abstract class which has to be extended by other classes.

We override the Base::msg() in Derived class. It is to be noted that when we create object of Base, compiler gives error.

Pure virtual functions with definitions

It turns out, we can provide definition to pure virtual function. We can do that by defining the function outside as shown below:

class Base
{
public:
    virtual void msg() const = 0;
};
 
void Base::msg() const
{
    std::cout << "Base" << '\n';
}
 
class Derived : public Base
{
public:
    void msg() const override
    {
        Base::msg();
        std::cout << "Derived msg" << '\n';
    }
};
 
int main(int argc, char const *argv[])
{
    Derived d;
    d.msg();
 
    return 0;
}

We can then use the Base::msg function inside the Derived::msg as shown in the example.

However, this is not commonly used feature.

Virtual table and pure virtual functions

Classes having pure virtual functions still have virtual table for consistency. However, the table entry point to a null pointer or a generic function giving error.

References

  1. https://www.learncpp.com/cpp-tutorial/pure-virtual-functions-abstract-base-classes-and-interface-classes/