Pure virtual (abstract) functions and abstract base classes
So far, all of the virtual functions we have written have a body (a definition). However, C++ allows you to create a special kind of virtual function called a pure virtual function (or abstract function) that has no body at all! A pure virtual function simply acts as a placeholder that is meant to be redefined by derived classes.
To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0.
#include <string_view>
class Base
{
public:
std::string_view sayHi() const { return "Hi"; } // a normal non-virtual function
virtual std::string_view getName() const { return "Base"; } // a normal virtual function
virtual int getValue() const = 0; // a pure virtual function
int doSomething() = 0; // Compile error: can not set non-virtual functions to 0
};
When we add a pure virtual function to our class, we are effectively saying, “it is up to the derived classes to implement this function”.
Using a pure virtual function has two main consequences: First, any class with one or more pure virtual functions becomes an abstract base class, which means that it can not be instantiated! Consider what would happen if we could create an instance of Base:
int main()
{
Base base {}; // We can't instantiate an abstract base class, but for the sake of example, pretend this was allowed
base.getValue(); // what would this do?
return 0;
}