1. Why do we need inheritance in C++?
Inheritance involves creating new objects by directly acquiring the attributes and behaviors of other objects and then extending or specializing them. This can not only save programmers time (no need to reinvent the wheel), but it also adds extra functionality around backwards compatibility, hierarchy, inheritance, shared behavior, etc.
2. Give a simple example of objects in the real world that could be modelled in C++ using inheritance.
Fruit. Consider apples and bananas. Although apples and bananas are different fruits, both have in common that they are fruits. And because apples and bananas are fruits, simple logic tells us that anything that is true of fruits is also true of apples and bananas. For example, all fruits have a name, a color, and a size. Therefore, apples and bananas also have a name, a color, and a size. We can say that apples and bananas inherit (acquire) these all of the properties of fruit because they are fruit. We also know that fruit undergoes a ripening process, by which it becomes edible. Because apples and bananas are fruit, we also know that apples and bananas will inherit the behavior of ripening.
1. What is a superclass and what is a subclass?
Inheritance in C++ takes place between classes. In an inheritance (is-a) relationship, the class being inherited from is called the parent class, base class, or superclass, and the class doing the inheriting is called the child class, derived class, or subclass.
2. How would you write a public inheritance in C++?
After the class declaration, use a colon, the word âpublicâ, and the name of the class we wish to inherit. This is called public inheritance.
3. In what ways can a subclass extend the functionality of a superclass?
Inheriting from a base class means we donât have to redefine the information from the base class in our derived classes. We automatically receive the member functions and member variables of the base class through inheritance, and then simply add the additional functions or member variables we want. This not only saves work, but also means that if we ever update or modify the base class (e.g. add new functions, or fix a bug), all of our derived classes will automatically inherit the changes!