- Why do we need inheritance in C++?
Inheritance is super useful to use of members of an already existing class. So if we create a class that can also make good use of members from an already existing class, but also has it’s own specific members, we can use inheritance.
- Give a simple example of objects in the real world that could be modelled in C++ using inheritance.
F. e. We have a class called people. Here we will store and process all data that apply to all people, like name, age, height, nationality, and so on…
Then we can have an additional classes for profession and religion.
In this additional classes we maybe can store and process data that, besides name, age, height, nationality, also take into account peoples jobs, or peoples religious beliefs.
By inheriting the peoples class into the profession and religion class, we can save code, only add the specific type of information or processing that is needed and also lay a good foundation for making adjustments to our project with minimum effort.
1. What is a superclass and what is a subclass?
A superclass, or base class or parent class, is the class we inherit data structure from.
2. How would you write a public inheritance in C++?
class JobClass: public People //Inheriting the People Class to JobClass{
//DoStuffHere
}
3. In what ways can a subclass extend the functionality of a superclass?
With subclasses, we can add specific information or processes, that we only want to apply to specific data structure. For example: People class stores age, name, height,… Then in JobClass we inherit the People information and add more specific data like Profession, Education, Years in Profession, and so on…