P A R T I
1. Why do we need inheritance in C++?
Object composition allows us to build “has-a” relationships with the constituent parts. However, object composition is just one of the two major ways that C++ enables us to construct classes. The second way is through inheritance, which allows us to build “is-a” relationships. For example, 386, 486 and Pentium are all computer processors. The 386 is-a computer processor and the 486 is-a computer processor too. We need inheritance because when the above is applied in practical terms, it allows us to inherit code from other classes that have this is-a relationship. This helps us avoid code duplication.
2. Give a simple example of objects in the real world that could be modelled in C++ using inheritance.
Fruit – a peach is-a fruit and a banana is-a fruit.
P A R T II
1. What is a superclass and what is a subclass?
In an inheritance (is-a) relationship, the class being inherited from is called the superclass, and the class doing the inheriting is called the subclass.
2. How would you write a public inheritance in C++?
The example below is where we want BaseballPlayer to inherit details (e.g. name and age) from the Person class. It’s better to use inheritance here rather than just enter name and age again into BaseballPlayer because if we use inheritance, any updates made to the Person class will automatically be reflected in the BaseballPlayer class too. This works because a baseball player is-a person. To do this, we add a colon after BaseballPlayer followed by “public Person”.
Example:
class BaseballPlayer : public Person{
public:
// Your code here
};
3. In what ways can a subclass extend the functionality of a superclass?
A subclass inherits all the functions and variables from the superclass. It can then also define its own functions and variables too.