Skip to main content
Engineering LibreTexts

4.9: Types of Inheritance

  • Page ID
    34666
  • Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
    Below image shows the combination of hierarchical and multiple inheritance:

    Classes A and C inherit from class B, while classes D and F inherit from class E. Classes B and E, in turn, inherit from class G

    // C++ program for Hybrid Inheritance 
    #include <iostream> 
    using namespace std; 
    
    // base class  
    class Vehicle  
    { 
      public: 
        Vehicle() 
        { 
          cout << "This is a Vehicle" << endl; 
        } 
    }; 
    
    //base class 
    class Fare 
    { 
        public: 
           Fare() 
        { 
            cout<<"Fare of Vehicle\n"; 
        } 
    }; 
    
    // first child class  - only inherits from Vehicle
    class Car: public Vehicle 
    {
        public:
        Car()
        {
            cout << "Driving my car" << endl;
        }  
      
    }; 
    
    // second child class - inherits from BOTH Vehicle and Fare
    class Bus: public Vehicle, public Fare 
    {
        public:
        Bus()
        {
            cout << "Riding the bus" << endl;
        }  
          
    }; 
      
    // main function 
    int main() 
    {    
        // creating object of the chcild class will 
        // invoke the constructor of base class - BOTH Vehicle and Fare
        Bus obj2; 
        
        // creating a car object would NOT
        // invoke the constructor for Fare
    
        return 0; 
    } 

    Output:

    This is a Vehicle
    Fare of Vehicle
    Riding the bus
    

    Notice that if we were to create an Car object that the Fare constructor is NOT called.

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