Inheritance

Inheritance facilitates the creation of complex class relationship by allowing one class to inherit the properties and behaviors of another. This concept is crucial in  object-oriented programming, providing a way to model an “is-a” relationship between classes.

Understanding Inheritance Relationship

Inheritance relationship involves two classes: the parent class (also known as the base class or superclass) and the child class (derived class or subclass). The child class inherits attributes and behaviors from the parent class, establishing an is-a relationship.

Example:

class Fruit {
public:
    std::string m_name;

    Fruit(std::string_view name) : m_name(name) {}
};

class Apple : public Fruit {
public:
    Apple(std::string_view name) : Fruit(name) {}
};

class Banana : public Fruit {
public:
    Banana(std::string_view name) : Fruit(name) {}
};

In this hierarchy, Apple and Banana are both types of Fruit. The : public Fruit notation that both Apple and Banana inherit from Fruit.

Benefits of Inheritance

Code Reusability:

  • Inherited classes reuse the functionality of their parent classes, avoiding code duplication.

Maintenance Ease:

  • Updates or modifications the the base class automatically propagate to derived classes, ensuring consistency.

Modeling Real-world Relationships:

  • Inheritance allows the modeling of real-world relationship, reflecting the “is-a” connection between entities.