Understanding Inheritance in OOP

3

The example below explains inheritance, an important property of OOP languages.

We have three classes: living, animal & dog. The dog inherits all the characteristics of living & animal base classes however, the plant does not(being an instance of just the living class).

#include<iostream>
using namespace std;
class living
{
      int energy;
      public:
                void getenergy()
                {
                     cout<<"Gets energy"<<endl;
                     }
};
class animal:public living
{
      int feet;
      public:
                void move()
                {
                     cout<<"It moves"<<endl;
                     }
};
class dog:public animal
{

      int tail;
      public:
                void bark()
                {
                     cout<<"It barks"<<endl;
                     }
};
int main()
{
    living plant;
    plant.getenergy();

    dog phoenix;
    phoenix.getenergy();
    phoenix.move();
    phoenix.bark();

    system("pause");
    return 0;
}

The dog inherits the properties of animal which inherits the properties of living. Hence, this inheritance is an example of “Multi-level” inheritance.

Share.

3 Comments

Leave A Reply