C++

Inheritance

Inheritance allows a new class (called the Derived/Child class) to inherit the attributes and methods of an existing class (called the Base/Parent class). This promotes code reusability and establishes a hierarchical relationship between classes

To inherit from a class, a colon (:) followed by an access specifier (public, protected, or private) and the name of the base class is used.

class BaseClass {
    // Base members
};

class DerivedClass : public BaseClass {
    // Derived members
};

The access specifier determines how the public and protected members of the base class behave inside the derived class.

Private variables and methods in base class remains private in derived class.

Public variables and methods in base class remains public in derived class.

Protected variables and methods in base class remains protected in derived class.

To illustrate, inheritance, we will create a fruit class and create other types of fruits to inherit the fruit class.

#include <iostream>
using namespace std;
class Fruit{
    public:
    string name;
    string shape;
    string color;
    protected:
    double weight;
};
class Mango : public Fruit{
    public:
    Mango(){
        cout << "Mango inherited from fruit class" << endl;
    }
    void setWeight(double w){
       weight = w;
    }
    double getWeight(){
        return weight;
    }
};
int main() {
    Mango mango;
    mango.name = "Mango";
    mango.shape = "Oval";
    mango.color = "Yellow";
    mango.setWeight(2);
    cout << "Fruit: " << mango.name << endl;
    cout << "Shape: " << mango.shape << endl;
    cout << "Color: " << mango.color << endl;
    cout << "Weight: " << mango.getWeight() << endl;

    return 0;
}

Notes:

  1. Protected attributes cannot be accessed when the object of the inherited class is created
  2. To access protected attributes write a set and get methods in the inherited class to assign and access the protected values.
  3. Protected attributes and methods can only be accessed in the inherited class and not the object.