An abstract class (sometimes referred to as an abstract base class) is a class in C++ with at least one pure virtual function. A virtual function is a function that is declared in a base class and is then declared again in a derived class with the same parameter list. The virtual keyword is used to mark the function as virtual. Here is an example of a virtual function in a base class and its derived, along with a driver function that will show what happens.


#include 

using namespace std;

struct Base {
  virtual void foo();
};

struct Derived : Base {
  virtual void foo();
};

void Base::foo() {
  cout << "Base::foo() was called.\n";
}

void Derived::foo() {
  cout << "Derived::foo() was called.\n";
}

int main() {
  Base* b = new b;
  b.foo();
  delete b;
  b = new Derived;
  b.foo();
  delete b;
  return 1;
}

This program outputs -
Base::foo() was called.
Derived::foo() was called.

What, then, is a pure virtual function, and how do these fit into abstract classes? Pure virtual functions are simply functions that have no implementation in the base class, relying on derived classes to provide their own implementations. This means that no runtime instances (objects) can be created from the base class - these classes only exist to act as generic blueprints for other classes. This can, when used correctly, really help tidy up your class hierarchy.

You define a pure virtual functions like this -

virtual void foo() = 0;

Then derived classes simply declare the function as normal, ie. -

void foo();

Note that because you cannot create runtime instances of abstract classes, this will fail -


class Abstract { virtual void foo() = 0; };

int main() {
  Abstract a; // Error here.
}

It is, of course, perfectly legal to create pointers such as Abstract* a; for the purpose of dynamic runtime casting.