Object Oriented Advanced

Basics

Syntax of Inheritance

Advanced: Adapter pattern

We can get a little creative with the inheritance syntax and deploy an "Adapter pattern":

Basic Inheritance pattern

Let us learn by studying an example.

Abstract classes

Override

A base class can define method(s) that could have override behavior:

One question to ask in the code snippet above is that what happens if the base class changes its method name? In this case, the intent was for another_animal to override, but it no longer overrides anything. This is the reason the override keyword was invented.

Let us use C++11 syntax to use the override keyword and see what happens when a method is intending to override a function but it doesn't do so:

Pure Virtual

A base class can provide default functionality or mandate that the child class inheriting the base (parent) class has to provide a certain functionality. It would look like this:

Example 1

Example 2

Video Game Example

Interfaces

An interface abstracts the implementation and enables unit-testing on the code. In other words, an interface is an abstract class that decouples the implementation from the interface, which allows changing or adding new implementations without affecting the rest of the program.

Polymorphism: The code below demonstrates polymorphism through the use of the interface. The test_communication function can take any object that implements the Communicable interface, showcasing how polymorphism enables the writing of more flexible and reusable code.

Example 1

In the example below, the interface ensures that any class that implements it will have a send method, but does not commit to how the sending is done, which is polymorphic.

Example 2

Exercise

Let us continue working on the examples below and practice more uses of interfaces.

  1. Create an interface that returns low threshold level for health
  2. Create an interface that returns when a character should attack
  3. Write two classes that inherit and implement the GameCharacter class
  4. Write a main function to invoke perform_action() on the two classes

 

Back to top