Home C++ Tutorial C++ Program to show inheritance using different levels

C++ Program to show inheritance using different levels

by Anup Maurya
20 minutes read

In this article, you’ll learn about how to make C++ program to show inheritance using different levels with explanation.

What is Inheritance?

In C++, inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class.

C++ Program to show inheritance using different levels

#include <iostream>

class Animal {
public:
    void eat() {
        std::cout << "The animal is eating." << std::endl;
    }
};

class Mammal : public Animal {
public:
    void breathe() {
        std::cout << "The mammal is breathing." << std::endl;
    }
};

class Dog : public Mammal {
public:
    void bark() {
        std::cout << "The dog is barking." << std::endl;
    }
};

int main() {
    Dog dog;

    dog.eat();
    dog.breathe();
    dog.bark();

    return 0;
}

In this program, we define a base class Animal that has a function eat(). We then define a subclass Mammal that inherits from Animal and has a function breathe(). Finally, we define another subclass Dog that inherits from Mammal and has a function bark().

In the main function, we create an instance of Dog and call its eat(), breathe(), and bark() functions. Because Dog inherits from Mammal, which in turn inherits from Animal, it inherits all of their functions as well. This means that we can call eat() and breathe() on a Dog object, even though they are defined in its parent classes.

The output of the program is:

The animal is eating.
The mammal is breathing.
The dog is barking.

That’s an example of how to demonstrate inheritance using different levels in C++. Inheritance allows a subclass to inherit properties and behaviors from its parent classes, and allows for code reuse and abstraction. Subclasses can further refine or add to the properties and behaviors inherited from their parent classes, creating a hierarchical structure of classes that models the real world or an abstract concept.

related posts

Leave a Comment

Enable Notifications OK No thanks