18.7 — Pure virtual functions, abstract base classes, and interface classes

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.

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:

Because there’s no definition for getValue(), what would base.getValue() resolve to?

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 pure virtual function example

Let’s take a look at an example of a pure virtual function in action. In a previous lesson, we wrote a simple Animal base class and derived a Cat and a Dog class from it. Here’s the code as we left it:

We’ve prevented people from allocating objects of type Animal by making the constructor protected. However, there are two problems with this:
1) The constructor is still accessible from within derived classes, making it possible to instantiate an Animal object.
2) It is still possible to create derived classes that do not redefine function speak().

For example:

This will print:

Betsy says ???

What happened? We forgot to redefine function speak(), so cow.Speak() resolved to Animal.speak(), which isn’t what we wanted.

A better solution to this problem is to use a pure virtual function:

There are a couple of things to note here. First, speak() is now a pure virtual function. This means Animal is now an abstract base class, and can not be instantiated. Consequently, we do not need to make the constructor protected any longer (though it doesn’t hurt). Second, because our Cow class was derived from Animal, but we did not define Cow::speak(), Cow is also an abstract base class. Now when we try to compile this code:

The compiler will give us a warning because Cow is an abstract base class and we can not create instances of abstract base classes (Line numbers are wrong, because the Animal class was omitted from the above example):

<source>(33): error C2259: 'Cow': cannot instantiate abstract class
<source>(20): note: see declaration of 'Cow'
<source>(33): note: due to following members:
<source>(33): note: 'const char *Animal::speak(void) const': is abstract
<source>(15): note: see declaration of 'Animal::speak'

This tells us that we will only be able to instantiate Cow if Cow provides a body for speak().

Let’s go ahead and do that:

Now this program will compile and print:

Betsy says Moo

A pure virtual function is useful when we have a function that we want to put in the base class, but only the derived classes know what it should return. A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.

Pure virtual functions with bodies

It turns out that we can define pure virtual functions that have bodies:

In this case, speak() is still considered a pure virtual function because of the “=0” (even though it has been given a body) and Animal is still considered an abstract base class (and thus can’t be instantiated). Any class that inherits from Animal needs to provide its own definition for speak() or it will also be considered an abstract base class.

When providing a body for a pure virtual function, the body must be provided separately (not inline).

For Visual Studio users

Visual Studio mistakenly allows pure virtual function declarations to be definitions, for example

This is wrong and cannot be disabled.

This paradigm can be useful when you want your base class to provide a default implementation for a function, but still force any derived classes to provide their own implementation. However, if the derived class is happy with the default implementation provided by the base class, it can simply call the base class implementation directly. For example:

The above code prints:

Sally says buzz

This capability isn’t used very commonly.

Interface classes

An interface class is a class that has no member variables, and where all of the functions are pure virtual! In other words, the class is purely a definition, and has no actual implementation. Interfaces are useful when you want to define the functionality that derived classes must implement, but leave the details of how the derived class implements that functionality entirely up to the derived class.

Interface classes are often named beginning with an I. Here’s a sample interface class:

Any class inheriting from IErrorLog must provide implementations for all three functions in order to be instantiated. You could derive a class named FileErrorLog, where openLog() opens a file on disk, closeLog() closes the file, and writeError() writes the message to the file. You could derive another class called ScreenErrorLog, where openLog() and closeLog() do nothing, and writeError() prints the message in a pop-up message box on the screen.

Now, let’s say you need to write some code that uses an error log. If you write your code so it includes FileErrorLog or ScreenErrorLog directly, then you’re effectively stuck using that kind of error log (at least without recoding your program). For example, the following function effectively forces callers of mySqrt() to use a FileErrorLog, which may or may not be what they want.

A much better way to implement this function is to use IErrorLog instead:

Now the caller can pass in any class that conforms to the IErrorLog interface. If they want the error to go to a file, they can pass in an instance of FileErrorLog. If they want it to go to the screen, they can pass in an instance of ScreenErrorLog. Or if they want to do something you haven’t even thought of, such as sending an email to someone when there’s an error, they can derive a new class from IErrorLog (e.g. EmailErrorLog) and use an instance of that! By using IErrorLog, your function becomes more independent and flexible.

Don’t forget to include a virtual destructor for your interface classes, so that the proper derived destructor will be called if a pointer to the interface is deleted.

Interface classes have become extremely popular because they are easy to use, easy to extend, and easy to maintain. In fact, some modern languages, such as Java and C#, have added an “interface” keyword that allows programmers to directly define an interface class without having to explicitly mark all of the member functions as abstract. Furthermore, although Java (prior to version 8) and C# will not let you use multiple inheritance on normal classes, they will let you multiple inherit as many interfaces as you like. Because interfaces have no data and no function bodies, they avoid a lot of the traditional problems with multiple inheritance while still providing much of the flexibility.

Pure virtual functions and the virtual table

Abstract classes still have virtual tables, as these can still be used if you have a pointer or reference to the abstract class. The virtual table entry for a pure virtual function will generally either contain a null pointer, or point to a generic function that prints an error (sometimes this function is named __purecall) if no override is provided.

18.8 -- Virtual base classes
18.6 -- The virtual table

162 comments to 18.7 — Pure virtual functions, abstract base classes, and interface classes

  • Kolunikus

    So if a base class with any purely virtual functions can't be instantiated, what kind of object is baseRef in the following code snippet?

    The output this creates is:

    Base object constructed
    Derived object constructed
    I did something!
    Derived object destroyed
    Base object destroyed

    Wouldn't it be more accurate to say "an abstract base class can't be INDEPENDENTLY instantiated"? Because it looks like the object gets instantiated just fine in the above snippet. Or am I missing something?

    • Alex

      BaseRef is a reference to a Base. References aren't objects in C++. The object is actually instantiated when we define Derived variable d.

      • Kolunikus

        Okay, I get the bit about the baseRef, I think. It's just some sort of "lens" through which only the Base part of the Derived object d can be seen.

        I guess my confusion is more about terminology than about concepts. It seems "instantiation" means more than just a constructor call, it refers to the creation of a full independent object, which the Base part of d is not. Is that correct?

        • Alex

          Yes, instantiation refers to creation of the full object. This can involve multiple constructor calls, either by virtue of derivation or chained constructors.

  • anas ali

    1. Write a class Shape that has one pure virtual function draw, then create three child classes Circle, Square and Oval. Child classes should inherit the Shape class and override the Operations function according to the name of the class. In main function create the reference object of Shape class and assign the reference of each child class and call the draw function with each object.

    can anyone solve this ??

    • Rishi


  • yeokaiwei

    "C:\Test.cpp(141) : error C2259: 'Cow' : cannot instantiate abstract class due to following members:
    C:Test.cpp(128) : see declaration of 'Cow'
    C:\Test.cpp(141) : warning C4259: 'const char *__thiscall Animal::speak(void)' : pure virtual function was not defined"

    May I ask what compiler this is?

  • Tim

    >>In this case, speak() is still considered a pure virtual function (even though it has been given a body, because of the “= 0”) and Animal is still considered an abstract base class

    Shouldn't it be rephrases as to be less confusing:
    In this case, speak() is still considered a pure virtual function because of the “= 0”(even though it has been given a body) and Animal is still considered an abstract base class

    >>In other words, the class is purely a definition, and has no actual implementation.
    shouldn't it be " the class is purely a declaration, ..."?

    • nascardriver

      > Shouldn't it be rephrases
      Agreed, lesson updated

      > the class is purely a declaration

  • Tim

    This might seem to be a very dump question and nonsense code example. But I was curios to know. Why we can't create objects of Animal class(Base) inside a method of a derived class and I got the 'protected' access warning while protected members are accessible through derived classes.

    • nascardriver

      You can only access `protected` members of the current object (`this`). `animal` in `printAnimal()` is not the current object, so you can't access any of its `protected` members.

  • Stefan

    The body of the pure virtual function speak should have matching const-ness to the declaration:

    should be

  • Stefan


    If a interface has only pure virtual methods, it means that it will have its own vtable. Therefore, it means that an interface has a data member: the vptr. Is it right?

    On the other hand, supposing a Derived class defines a virtual method which is not inherited from Base class (be it Interface or not). This virtual method will get an entry in derived class vtable. Can this method be called via a reference to Base class that points to a Derived object? See example below:

    class Base
          virtual void print() = 0;

    class Derived:public Base
            int data{0};
            void print(){cout<<"Derived"<<endl;};
             int getData() const{return data;};

    int main()
        Derived d{};
        Base& bref{d};

            //here, bref should access vptr from the Base part of the d object, which points to Derived vtable. However, it throws error as the method is not member of base. How come?
        return 0;

    • nascardriver

      You can only call functions that exist in `Base`. The compiler has no way of knowing that `bref` refers to a `Derived`. It could just as well refer to something that doesn't have a `getData` function. The only thing it knows for sure is that `bref` has all functions that are in `Base`, not matter what type `bref` really is.

  • Remy


    Can we virtual override an overloaded arithmetic operator the member function way? I found this solution but based from what we've learned I suspect it to be wrong maybe? Due to it not having a matching parameter.

    If it's possible may I get an example?

    • nascardriver

      I don't understand what you're trying to do. Please post an example where you state what's happening and what you want to happen. I'm also curious as to why you need virtual operators.

      • Remy

        Well, it all started from a previous chapter recommending not using virtual assignment but said it could be done. You know like when you're a kid told not to touch the stove and you go touch the stove? So I started experimenting. And I thought what about other virtual operators? After going through those chapters again I realized I don't know how to do it. The signature would be different. What's going to be the right operand? Therefore not a valid override. If assignment operator can be virtual then it makes sense that other operator could be virtual too. And I'm trying to see how it's done.

        For the sake of it I'm going to show you sth that really doesn't make sense.

        You're curious as to why I need virtual operators, and I'm curious about..I don't know what I'm curious about I'm just curious.
        And that's sad. :(
        Man I wanna touch the stove..

        • nascardriver

          I'm assuming all children of `INumber` can be added together, for example Float+Fraction would be allowed.
          Every child of `INumber` has to implement and every operator with every other child, because all these operators function differently. Fraction+Integer has to do something else than Fraction+Float.
          `INumber` would have `operator+(INumber)`, because you need to know what type the parameter is to be able to compute it. `INumber` needs a virtual `operator+` for every child type of `INumber`, and every child has to override these operators.

          The general problem is that you have a different representation for every number type. What you might be able to do is add a representation that works with every number type there is. If you're okay with floating point errors, that representation could simply be a `long double`. Then you only need the `operator+(INumber)` (With different return types in every child class)

          The problem continues with your return types. Covariant return types have to be pointers or reference, you can't return by value. Your types are just too different to make this work with inheritance. Yes they are all numbers, yes they all have a set of operators, but apart from that they have nothing in common. You can make `INumber` hold the actual value, then return `INumber` from your operators, or you can add another class between `INumber` and your number types that holds the value, then return that.

          The way you're using the numbers in `main` doesn't require inheritance at all. If every number type has an `operator+` for every other number type, or you have some intermediate representation (For example the `.value()` function from above), you can do this with templates or `auto` parameters.

          These functions will return the type that `operator+` returned. If `a` is a `Fraction` and `Fraction::operator+` returns a `Fraction`, these functions return a `Fraction` as well.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]