Skip to main content

Most Visited Blog

How to Install minGW C++ compiler for Windows - Cyborg Coding

Hierarchical Inheritance in C++ - Cyborg Coding

Hierarchical Inheritance in C++ is a type of inheritance where a derived class is derived from more than one base class. This means that a single derived class inherits properties and methods from multiple base classes.

For example, consider a base class called "Animal" which contains properties and methods related to animals, such as "breathe()" and "eat()". Another base class, called "Mammals", contains properties and methods specific to mammals, such as "milk()" and "hair()". A derived class, called "Human", can inherit from both the "Animals" and "Mammals" base classes, inheriting properties and methods from both.

Here is an example of how the classes could be implemented in C++:

class Animals
{
public:
    void breathe() { cout << "Breathing" << endl; }
    void eat() { cout << "Eating" << endl; }
};

class Mammals: public Animals
{
public:
    void milk() { cout << "Producing milk" << endl; }
    void hair() { cout << "Growing hair" << endl; }
};

class Human: public Mammals
{
public:
    void talk() { cout << "Speaking" << endl; }
};

In the example above, the "Human" class is derived from the "Mammals" class, which is derived from the "Animals" class. The "Human" class inherits all the properties and methods of the "Animals" and "Mammals" classes, including "breathe()", "eat()", "milk()", and "hair()". Additionally, the "Human" class has its own unique method, "talk()".

In this example, we can see that the derived class "Human" is inheriting the properties and methods of the base classes "Animals" and "Mammals"

It's worth noting that in hierarchical inheritance, a derived class can access all the public and protected members of its base classes, but not the private members. Also, if a base class has a method with the same name as a method in another base class, the derived class will only be able to access the one inherited from the base class specified first.

One potential use case for hierarchical inheritance is in creating a simulation or game where different types of objects need to share common properties and methods, but also have unique properties and methods. For example, in a simulation of a zoo, all animals would have a "breathe()" method, but only mammals would have a "milk()" method, and only humans would have a "talk()" method.

However, it's also worth noting that hierarchical inheritance can lead to complex and hard to maintain code, and it's often recommended to use composition instead when possible.

In conclusion, Hierarchical Inheritance in C++ allows a derived class to inherit properties and methods from multiple base classes, allowing for the reuse of code and the ability to create complex class hierarchies. However, it can lead to complex and hard to maintain code, and it's often recommended to use composition instead when possible.

Comments