C++ Pure Virtual Functions v.s. Ordinary Virtual Functions

31 Jan 2013

A pure virtual function is a virtual function that has no definition (no body) at all. It simply acts as a placeholder that is meant to be redefined by the derived class.

To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0.

class Base
{
    public:

        // a normal non-virtual function    
        const char* func1() { return "Hi"; }        

        // a normal virtual function
        virtual const char* func2() { return "Base"; }      

        // a pure virtual function
        virtual int func3() = 0;
};

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. Second, any derived class must define a body for this function, or that derived class will be considered an abstract base class as well.

A ‘non-pure’ normal virtual function, on the contrary, must have a body defined (although it could be empty in the body). If you don’t define the body and don’t make the virtual function ‘pure’ (by assigning value 0) either, you will get a linking error saying: Undefined reference to vtable for …. An example of normal virtual function is a virtual destructor, which appears frequently in various base classes.

So, if you don’t provide any implementation for the virtual destructor, you get this error. Check out the bottom of this page for such concept.