Skip to main content
Engineering LibreTexts

4.8: Types of Inheritance

  • Page ID
    34665
  • Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than one derived class is created from a single base class.

    Classes A and C inherit from class B, while classes B inherits from class F. Class E inherits from both class F and class G.

     

    // C++ program to implement  
    // Hierarchical Inheritance 
    #include <iostream> 
    using namespace std; 
      
    // base class 
    class Vehicle  
    { 
      public: 
        Vehicle() 
        { 
          cout << "This is a Vehicle" << endl; 
        } 
    }; 
    
    // first sub class  
    class Car: public Vehicle 
    {
        public:
        Car()
        {
          cout << "This is a Car" << endl;
        } 
      
    }; 
    
    // second sub class 
    class Bus: public Vehicle 
    { 
        public:
        Bus()
        {
          cout << "This is a Bus" << endl;
        } 
          
    }; 
    
    // main function 
    int main() 
    {    
        // creating object of sub class will 
        // invoke the constructor of base class 
        Car obj1; 
        Bus obj2; 
    
        return 0; 
    } 

    Output - For each of the objects the parent class constructor gets called as well as the child class constructor.

    This is a Vehicle
    This is a Car
    This is a Vehicle
    This is a Bus
    

    by-sa.png
    Contributed by Harsh Agarwal
    Geeks for Geeks

    • Was this article helpful?