In C++ a pure abstract base class is a contract

This tip submitted by Marty Corbett on 2012-01-31 17:00:19. It has been viewed 25935 times.
Rating of 5.3 with 152 votes



A pure abstract base class is one in which all of its member functions are declared as virtual and have no body (=0). This can be thought of as a contract between the user and the implementer of a class.

Any class that derives from the pure abstract base class must provide the behavior for all of the member functions (in the example below this is class B) in the exact form as specified by the "contract".

From a usage perspective the details of what will be provided by the derived class are specified, but not how it will be provided.

Therefore, we can have one person implement the behavior in the derived class and another person implement the usage of that behavior.

#include 

class Contract
{
  // Any derived classes 
  // must implement foo
  virtual short foo(void) = 0;
};

class B : public class Contract
{
  // Adhere to the contract and
  // provide behavior for foo.
  short foo(void) { return 2; }
};

int main(int argc, char *argv[])
{
  // Use the contract
  Contract *pContract = new B;

  std::cout 
    << "foo=" 
    << pA->foo() 
    << std::endl;


  delete pContract;
  return 0;
}

Now let's say that we have our contract in place and we need a slightly different implementation.  Simple:

class C : public class Contract
{
  // Adhere to the contract and
  // provide behavior for foo.
  short foo(void) { return 4; }
};



The main code knows that the rules of the contract have been adhered to so it can use class C in the same way as it used class B by changing the allocation in main as follows:

  // Use the contract
  Contract *pContract = new C;


This structure provides a mechanism to specify an interface, "contract", between two entities prior to any code ever being written. Another benefit is that the contract allows testing of the interface without any of the final code on either side of the interface.




More tips

Help your fellow programmers! Add a tip!