1. Why do we need inheritance in C++?
For backwards compatibility, and to write less code.
2. Give a simple example of objects in the real world that could be modelled in C++ using inheritance.
I would say cultural rules would be a real world example of inheritance. Also work cultural rules would be a real world example of inheritance because everyone follows them in society or work respectively. There are different cultures in different parts of the world, but everyone believes his or her culture is correct even though it is 100% based on inheritance.
1. What is a superclass and what is a subclass?
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++?
#include
class Person
{
// In this example, weāre making our members public for simplicity
public:
std::string m_name{};
int m_age{};
Person(const std::string& name = "", int age = 0)
: m_name{ name }, m_age{ age }
{
}
const std::string& getName() const { return m_name; }
int getAge() const { return m_age; }
};
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.