C++ - what is an abstract base class?

An abstract class cannot be instantiated. It contains at least one pure virtual function (a virtual function with no implementation) or is marked with the keyword abstract.


Since an abstract class can't be instantiated, it must serve as a base class to a derived class that can be instantiated. Hence Abstract Base Class (ABC).


  class ConsoleWriter
  {
  public:
      virtual void WriteLine(char* message) = 0; // a pure virtual function
  }
  

An abstract class can contain methods with an implementation. It is still abstract if it has at least one pure virtual function.


  class ConsoleWriter
  {
  public:
      virtual void WriteLine(char* message) = 0;
      
  private:
      void WriteLineHelper(char* message)
      {
          printf("%s\r\n", message);
      }
  }
  

This class has no pure virtual functions. I.e. all methods have an implementation, but the class is marked with the keyword abstract. The class is still abstract.


  class ConsoleWriter abstract
  {
  public:
      virtual void WriteLine(char* message)
      {
          printf("%s\r\n", message);
      }
  }
  

Ads by Google



Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath