Skip to main content
Engineering LibreTexts

4.6: Types of Inheritance in C++

  • Page ID
    34663
  • \( \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}}\)

    Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes.

    A derived class A that inherits from base classes B and C

    Syntax:

    class subclass_name : access_mode base_class1, access_mode base_class2, ....
    {
      //body of subclass
    };
    

    Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every base class must be specified.

    
    // C++ program to explain  
    // multiple inheritance 
    #include <iostream> 
    using namespace std; 
      
    // first base class 
    class Vehicle 
    { 
      public: 
        Vehicle() 
        { 
          cout << "This is a Vehicle" << endl; 
        } 
    }; 
      
    // second base class 
    class FourWheeler 
    { 
      public: 
        FourWheeler() 
        { 
          cout << "This is a 4 wheeler Vehicle" << endl; 
        } 
    }; 
      
    // sub class derived from two base classes 
    class Car: public Vehicle, public FourWheeler 
    {
        public:
        Car()
        {
          cout << "This vehicle is a 4 wheeldrive Car" << endl;
        } 
      
    }; 
      
    // main function 
    int main() 
    {    
        // creating object of sub class will 
        // invoke the constructor of base classes 
        Car obj; 
        return 0; 
    } 
    

    Output:

    This is a Vehicle
    This is a 4 wheeler Vehicle
    This vehicle is a 4 wheeldrive Car
    

     

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


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

    • Was this article helpful?