Extensibility

Extensibility refers to the concept of being able to add new (derived) classes, and hence behaviour, from a common base class.

 

Assuming the base class has a well defined interface, any new derived class can simply follow on using the same methods, implemented as required in the derived class and therefore extending the capabilities of the program.

 

Here's a derived class inheriting from a base class:

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

class Animal {
	protected:
		int legs = 2 ;
	public:
		virtual void makeNoise() {
			cout << "Mumblings from the primordial soup. Hmm, I've just grown " << legs << " legs!!" << endl ;
		}
	virtual ~Animal(){}
};

class Dog : public Animal {
	public :
		void makeNoise(){
			cout << "Woof! Dirty dog with " << legs * 2 << " canine legs." << endl ;
	}
		virtual ~Dog(){}
};

int main() {
	Animal cell ;
	Animal *ptr = & cell; //declare a Base class pointer
	ptr->makeNoise() ;  //invoke the method

	Dog rex ;  //declare a Dog object called rex
	ptr = &rex ;  //assign the address of rex to the Base class pointer
	ptr->makeNoise() ;  //invoke the method

	return 0;
}

Compile & Run:

Mumblings from the primordial soup. Hmm, I've just grown 2 legs!!
Woof! Dirty dog with 4 canine legs.

 

 

 

We can simply add more derived classes and continue using the same base class interface:

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

class Animal {
	protected:
		int legs = 2 ;
	public:
		virtual void makeNoise() {
			cout << "Mumblings from the primordial soup. Hmm, I've just grown " << legs << " legs!!" << endl ;
		}
	virtual ~Animal(){}
};

class Dog : public Animal {
	public :
		void makeNoise(){
			cout << "Woof! Dirty dog with " << legs * 2 << " canine legs." << endl ;
	}
		virtual ~Dog(){}
};

class Cat : public Animal {
	public :
		void makeNoise(){
			cout << "Meow. Cleaning my " << legs * 2 << " feline legs with claws!" << endl ;
	}
		virtual ~Cat(){}
};

class Spider : public Animal {
	public :
		void makeNoise(){
			cout << "Eeek. I've got " << legs * 4 << " spindly legs and venom!" << endl ;
	}
		virtual ~Spider(){}
};

int main() {
	Animal cell ;
	Animal *ptr = & cell; //declare a Base class pointer
	ptr->makeNoise() ;  //invoke the method

	Dog rex ;  //declare a Dog object called rex
	ptr = &rex ;  //assign the address of rex to the Base class pointer
	ptr->makeNoise() ;  //invoke the method

	Cat silver ;
	ptr = &silver ;
	ptr->makeNoise() ;

	Spider syd ;
	ptr = &syd ;
	ptr->makeNoise() ;

	return 0;
}

Compile & Run:

Mumblings from the primordial soup. Hmm, I've just grown 2 legs!!
Woof! Dirty dog with 4 canine legs.
Meow. Cleaning my 4 feline legs with claws!
Eeek. I've got 8 spindly legs and venom!

 

 

OK, these examples may seem overly simplified, but the idea is to focus upon just the one aspect in question - in this case extensibility

Leave a Reply