12.6 — 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:

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

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 also bodies:

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 (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).

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.

12.7 -- Virtual base classes
12.5 -- The virtual table

94 comments to 12.6 — Pure virtual functions, abstract base classes, and interface classes

  • Nitin

    Typo: define these function --> these functions.

  • Quoxa

    probably just a typo:

    In the sentence

    "...they will let you multiply inherit as many interfaces as you like.",

    I think you meant "multiple inherit" instead of "multiply inherit".

  • johnsmith29a

    There is one thing I don't quite understand. Why does an abstract class have a virtual table? *Vptr is set when you instantiate an object and it points to the virtual table of that object's class. Abstract classes can't be instantiated, so why would they need a virtual table?

    You wrote that "Abstract classes still have virtual tables, as these can still be used if you have a pointer or reference to the abstract class". But if I have a pointer to an abstract class, it actually points to an instance of a derived (non-abstract) class, so that derived class's virtual table will be used, right?

  • apple

    Hi Alex,

    Great thanks for this c++ tutorials and it helped me in understanding concepts very quickly. And it will be helpful if you add exercise problems. 🙂 🙂

  • jmgonet


    A tutorial like this is hard work, and I just want to say thanks. You helped me today.

    Take care!

  • Benjamin


    this is somewhat a redundant comment, but it was funny for me to see the following:

    I created an abstract class A by defining a pure virtual function. At the same time I made this function final. Clearly, I cannot instantiate an object from the abstract class A. Also I cannot write a class that inherits A, as it cannot override the virtual function.

    With one simple line I wrote an unusable class without creating a compiler error:

    I guess doing something like that nonsense (or is there some weird application?), but I think the compiler should at least give a warning that the developer did something absurd.

  • Nur

    Hello Alex
    Hope you are doing well. I have a question regarding to an Interface class. As you mentioned that pure virtual function should be assigned by the value 0, then it is called pure virtual function. And also you mentioned about pure virtual function with bodies which is outside of class definition for abstract class.Here is a little confusion, so I modified your program( Removed member data-es, access specifiers) to understand in depth the differences between interface and Abstract.
    As we know Interface class should be contained only pure virtual function and with no data members and etc. The question: Is the pure virtual function with body which is outside(with default implementation)considered to be Interface class or abstract class.

    Example for that is below shown Animal class.So, can we consider below Animal class as an Interface class (with pure virtual function with bodies)?

    class Animal  
        virtual const char* speak() = 0;
        virtual ~Animal(){}

    const char* Animal::speak()  // even though it has a body
        return "buzz";
    class Tiger:public Animal// derived class;
      std::string m_name;
       virtual ~Tiger(){}
       virtual const char*speak()
          return Animal::speak();
    int main()
        Tiger tg;

  • Lim Che Ling

    (12.2a. Rule: Apply the override specifier to every intended override function you write.)
    So we don't need to 'overwrite' virtual function in Derived class if the parent is abstract class, right?

    • Alex

      You don't need to, but your derived class will be an abstract class if it derives from an abstract parent and still has pure virtual functions.

  • David

    I'm confused by this: "When providing a body for a pure virtual function, the body must be provided separately (not inline)."

    When a body is provided inline, rather than separately, everything still seems to work as expected.

  • YMK

    Hi Alex,
    Great explanation of interfaces. I have a question though. Is C++ interface classes functionally the same as Swift's protocol? Even though conforming to a protocol doesn't involved inheritance like C++ does, at the crust of it both do the same thing. At least it seems like it to me.

    Kindly give me some insight on this thank you.

    • Alex

      I'm not familiar with Swift, but at a cursory glance, yes, it appears that Swift's protocol serves the same purpose. Java also provides first-class support for this via the interface keyword.

  • Ganesh Bhadane

    Hi Alex,

    I have a question about interfaces. Can I declare interfaces in structure? if yes, then how? And No, why?

    • Alex

      When you say "in structure" you mean using a struct? You can, but you shouldn't. Structs should only be used for plain data (no functions), and interfaces are all functions.

  • Kiran C K

    Hi Alex,
    Is there a way to overload a virtual function in the base class and use only the appropriate function in the derived class? i.e. define only one of the overloaded virutal functions

    • Alex

      Hi Kiran,

      I'm not clear on what you're asking here. Can you clarify?

      • Kiran

        Lets say an abstract class has a function with the same name but with different parameters. In such a case, is there a way that I provide body only for the required function in the derived class? I tried setting the function that I wont use as private but though it is private, it allows the main function to access that method and print the result. Here is the code:

        I am not sure if it is a compiler bug or security flaw or works as expected.

        • Alex

          This is working as expected. You're accesing func() through b, which is of type Base. In class Base, func() is public.

          • Nivetha

            Hi Alex,

            Can you please elaborate on this as it is bit confusing for me.
            In the above case,
            b's vptr will be pointing d's virtual table which will be having Derived::func(int, int) and will be resolved to the same right? But this funtion is declared private in Derived. How can it be accessible?

            • Alex

              Access controls are implemented at a class level and are enforced by the compiler. The fact that the function is private in Derived is irrelevant when accessing the function through a Base pointer. All the compiler sees is that the function in public in Base, and we're accessing through a Base object, so as far as it's concerned, everything is fine.

              • Dani

                I tried to accomplish it through this method:

                and the compiler complaint that by doing so, Base::func1(int, int) was being invalidated, even though it was not deleted on its declaration. Since that was the actual goal of doing so, is there a way to acheive it?

                • Alex

                  C++ won't let you delete a virtual function. There's no direct way to do what you want, but there's an interesting workaround using static_assert that's detailed here.

  • Alex

    The abstract class constructor is still called when you create an (non-abstract) object derived from the abstract class.

Leave a Comment

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