Software Design Patterns

Inheritance

Inheritance

There are 2 types of inheritance:

  • Interface inheritance
  • Implementation inheritance

Regardless of whether you inherit from a standard class, an abstract class, a pure virtual class, or an interface construct you get interface inheritance. This means that you inherit all the signatures of the base class.

When you inherit from a standard class or an abstract class (with partial implemtation) you have interface and  implementation inheritance, which means that all the functions that are implemented in the base class can be used by the subclass. This can be very useful when the subtypes' functions need to always work exactly the same, or nearly exactly the same as the superclass.

Implementation inheritance is extremely powerful because we get to reuse code for free, so why would we ever choose to use interface inheritance without implementation inheritance?

  • When classes should have same interface, but implentations vary.
  • So we can use multiple inheritance.
  • When the main point using a common interface was to gain the use of polymorphism.

This can be a difficult decision to make. Less experienced programmers will tend to always use implementation inheritance. This seems to make a lot of sense when you learn how powerful it is to be able implement a function once in the superclass and use that from every subclass, but as you become a more experienced programmer, you will begin see that there are many times when we really ONLY want to inherit the interface, and we can make other arrangements for reusing implemtation. In many languages you can only inherit from one 'class', but you can inherit from many 'interfaces'. If your subtypes need to implement multiple interfaces then you need to use interface inheritance only..

Let's say that you have a base class, and and it has a function that 50% - 75% of the time you will want to use that exact same implementation of that function in subclasses. In this case, we need to strongly consider NOT using implementation inheritance. Why not? Why not use implementation inheritance, and just override the function in the 50% - 25% of the classes that need a different implementation?

I won't take the time to get into all the detail of this scenario, but will refer you to look at the Strategy Pattern as it meant for exactly this type of situation.

0 Comments