Inheritance

Process of creating a new class from an existing class.

 

New class is know as the Derived, or Child or Subclass.

 

Existing class from which it was derived from is know as the Base, or Parent or Superclass.

 

 

*Note: In UML, Inheritance is shown as a large blank arrow head

 

Promotes code reuse and reduces code size.

 

Allows us to identify some shared members between objects

 

Overriding Parent methods for specific Child behaviour

 

Identify commonality, put into Parent, then let Child classes inherit

 

This technique implements what is referred to as the “Is-A” relationship.

e.g.

a car is a vehicle

a Ferrari is a car

Therefore a Ferrari is also a vehicle

 

The Child class inherits the Parent’s methods as follows:

Access by: Public Private Protected
Same class Yes Yes Yes
Derived class Yes Yes No
External class Yes No No

 

Public inheritance provides the Parent’s Public and Protected methods to the Child (as its own Public and Protected methods) but not its Private methods, these should be accessed using calls to the Parent’s Public methods.

 

Protected inheritance provides the Parent’s Public and Protected members as Protected members in the Child.

 

Private inheritance provides the Parent’s┬áPublic and Protected members as Private members in the Child.

 

A simple C++ code example:

Here, the two subclasses (Ducati and Yamaha) use the Parent Motorbike class. This Parent class is never called directly, but just acts to provide similar qualities (members) to the derived classes, in this case the ability to set the int speed. The Child classes then use their own methods unique for their own behaviour, in this case their public methods of getSpeed and saySpeed (just using different names to show they are different).

Leave a Reply