Skip to main content
Engineering LibreTexts

4.8: Types of Inheritance

  • Page ID
    34665
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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


    This page titled 4.8: Types of Inheritance is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?