Abstract Base Class

An abstract base class is a construct that is purely used to be inherited form, and cannot be instantiated on its own.

 

It is implemented by creating at least one pure virtual function within the class.  A pure virtual function is a special kind of virtual function that has no body and is assigned the value of 0.

 

The pure virtual function simply acts as a placeholder, that indicates that it is meant to be defined/overridden in a derived class.

 

Syntax:

virtual return_type function_identifier() = 0 ;

 

This forces derived class to define the pure virtual function, and if they don't they're also considered abstract classes (since they inherit their base class methods) and they too cannot be instantiated!

 

This technique ensures a specific design is followed, by forcing those pure virtual functions to be defined in the derived classes.

 

This example shows an abstract base class with its pure virtual functions on lines 10 and 11:

#include <iostream>
#include <string>
using namespace std;

class Vehicle {
	protected:
		int speed = 0 ;

	public:
		virtual void accelerate() = 0 ;
		virtual void brake() = 0 ;
		virtual ~Vehicle(){ }
};

class Bike : public Vehicle {
	public :
		void accelerate(){
			speed += 10 ;
			cout << "Bike speeding up to " << speed << " mph." << endl ;
	}
		void brake(){
			speed -= 10 ;
			cout << "Bike slowing down to " << speed << " mph." << endl ;
	}
		virtual ~Bike(){ }
};

int main() {

	Bike ducati ;
	Vehicle *ptr = &ducati;
	ptr->accelerate() ;
	ptr->accelerate() ;
	ptr->accelerate() ;
	ptr->brake() ;
	ptr->brake() ;

	return 0;
}

Compile & Run:

Bike speeding up to 10 mph.
Bike speeding up to 20 mph.
Bike speeding up to 30 mph.
Bike slowing down to 20 mph.
Bike slowing down to 10 mph.

 


 

As a (related) aside: An Interface Class is a type of class where all methods are pure virtual and it has no member variables! Therefore it cannot be instantiated and has no implementation, thus enforcing derived classes to define the functionality required. The benefit of this is that it provides the flexibility to derive specific implementations (e.g. email user or open an incident ticket) and enables extensibility to add new implementations that utilise the existing interface of the interface class.

Leave a Reply