Lesson 152 +10 XP

Pure Virtual Functions and Abstract Classes

Pure Virtual Functions and Abstract Classes

Sometimes a base class's job is to define the shape of a method without supplying the body. Every derived class must fill it in. For that, C++ gives pure virtual functions and abstract classes.

Pure virtual syntax

A pure virtual function is a virtual function with the text = 0 instead of a body:

class Animal {
public:
  virtual void sound() = 0;   // pure virtual
};

Note: virtual void sound() = 0; - the = 0 signals that the base provides no implementation.

The class becomes abstract

Any class with at least one pure virtual function is abstract. You cannot create an object of it:

Animal a;   // ERROR: cannot instantiate an abstract class

You can still hold a pointer or reference to it, which keeps polymorphism alive.

Derived classes must override

A concrete derived class must implement every pure virtual function. If it skips one, the derived class is abstract too:

class Dog : public Animal {
public:
  void sound() override { cout << "Woof"; }   // now Dog is concrete
};

Once sound() is supplied, Dog can be instantiated.

Interface classes

A class that is all pure virtual functions is often called an interface class. It is a contract: every class that inherits it must provide the required behaviors. The compiler enforces the contract.

TL;DR

  • virtual void f() = 0; declares a pure virtual function.
  • It has no body; the = 0 marks it pure.
  • The class becomes abstract and cannot be instantiated.
  • Derived classes must override every pure virtual function.
  • Interface classes are contracts of required behaviors.