All You Need to Know About Inheritance in C++

Published on Sep 05,2019 18 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

C++ is an Object-Oriented language. Data abstraction, Polymorphism, Encapsulation, and Inheritance are the cornerstones of OOP. In this post, we will understand what is inheritance? Types of inheritance in C++, and all the necessary concepts related to it from scratch. In the end, we will also look at the drawback of this powerful concept and try to solve it.

 

     

    What is Inheritance in C++

    Inheritance is one of the most powerful and widely used concepts in C++ or any other Object-oriented language. Understanding this concept requires a little knowledge of classes and objects. Using Inheritance, we can create a class that consists of general methods and attributes. This class can be inherited by other classes containing more specific methods.

    Inheritance in C++

    By doing this we don’t have to write the same functionalities again and again which saves time and increases the readability of code.

    Syntax:

    class derived_class: access_type base_class{
    
    // class body
    
    };

    Base class: The class which consists of all the general methods and attributes which can be shared by other classes to increase code readability is called a base class.

    Derived class: The class which consists of more specific methods and inherits a class is called a derived class. A derived class can also be a base class for some other derived class.

    If we create a class XYZ, with some attributes and methods. Now a class student will have some other attributes, but it will also include the elements of XYZ class and the same goes for a faculty class. Let’s see a diagram:

    Basic-inheritance-in-C++

    So, the student and faculty class will inherit from XYZ.

    Access specifier- We understood how a class can inherit another class. But some people might say that it is an unsafe method as all the attributes and methods of the base class or the parent class is shared with the child class or the derived class. For example, if a class ‘Bank’ is inherited by the class ‘customers’ and ‘investors’. Attributes of class ‘Bank’ such as ‘vaultpassword’, other customer-related information and private data is shared with the ‘customers’ and the ‘investors’ class which is unsafe.

    To solve the above problem C++ uses access specifiers to limit the access of base class attributes to the derived class. There are a total of 3 types of access specifiers in C++

    1. Public
    2. Private
    3. Protected

    The below table will give you a good understanding of what type of data can be accessed by derived class according to different access specifiers.

     

    Access SpecifierPublic DataPrivate DataProtected Data
    PrivateNot InheritedNot InheritedNot Inherited
    ProtectedProtectedPrivateProtected
    PublicPublicPrivateProtected

     

    Single Inheritance

    Single Inheritance can be considered as the plain vanilla form of inheritance. In single inheritance, a single class inherits from a base class.Single-inheritance

    #include <iostream>
    
    using namespace std;
    
    class Train{
        int Numberofwheels;
         int Numberofcoaches;
        public:
         void Traininfo(int n, int m){
            Numberofwheels = n;
            Numberofcoaches = m;
            }
            void showinfo(){
                cout<<Numberofcoaches<<"n"<<Numberofwheels<<"n";
            }
        };
        class BulletTrain : public Train{
            int flux;
            public:
             BulletTrain(int b){
                 flux = b;
                 }
                 
            void Magneticfield(){
                cout<<" The Magnetic field is turned ON with flux = "<<flux ;
            }     
            };
    int main()
    {
        BulletTrain bullettrain(10);
        bullettrain.Traininfo(0, 20);  //accessing member function of base class
        bullettrain.showinfo();         //accessing member function of base class
        bullettrain.Magneticfield(); //Using member function of derived class
        return 0;
    }

    Output:

    20

    0

    The magnetic field is turned ON with flux = 10

     

    Multilevel Inheritance

    This case of inheritance is called as Multilevel inheritance. The class in between the first and the last class is also known as an intermediate base class. What do you think, can the last class inherit members of the first class? Yes, it canMultilevel

    #include <iostream>
    
    using namespace std;
    class First {
        protected:
        int a;
        public:
        void getinfofirst(int x){
            a = x;
        }
        void showinfofirst(){
            std::cout << "Value of a = " <<a << std::endl;
        }
    };
    
    class Second : public First{
        protected:
        int b;
        int c;
        public:
        void getinfosecond(int y, int z){
            b = y;
            c = z;
        }
        void showinfosecond(){
            cout<<"Value of b = "<<b<<"n";
             cout<<"Value of c = "<<c<<"n";
        }
        
    };
    
    class Third : public Second{
        int d;
        public:
        void display(){
            d = b + c;          //Using member variables of class second
            showinfofirst();    //Using member function of class First
            showinfosecond();   //Using member function of class second
            cout<<"Value of d = "<<d<<"n";
            
        }
    };
    
    
    int main()
    {
        Third third;
        third.getinfofirst(10);
        third.getinfosecond(20, 30);
        third.display();
        return 0;
        
        
    }

    Output:

    Value of a = 10

    Value of b = 20

    Value of c = 30

    Value of d = 50

     

    Hierarchical Inheritance

    Certain problems cannot be solved with the help of single or multilevel inheritance. In hierarchical inheritance, more than 1 class inherit from a single base class.Heirarachial

    #include <iostream> 
    using namespace std; 
      
    
    class College  
    { 
      public: 
        College() 
        { 
          cout << "We are in class College" << endl; 
        } 
    }; 
    
    class Student: public College 
    { 
      
    }; 
      
    class Faculty: public College 
    { 
          
    }; 
      
    int main() 
    {    
        
        Student student; 
        Faculty faculty; 
        return 0; 
    }

    Output:

    We are in class College

    We are in class College

     

    Multiple Inheritance in C++

    We saw in hierarchical inheritance one base class had more than one derived class. In multiple Inheritance one derived class has more than one base class.

    #include <iostream> 
    using namespace std; 
      
      class One{
          protected:
          int a;
          public:
          void getinfoOne(int x){
              a = x;
          }
           };
    class Two {
        protected:
        int b;
        public:
        void getinfoTwo(int y){
            
            b = y;
        }
        
    };
    
    class Main : public One, public Two{
        
        public : 
            void Display(){
            std::cout << "Value of a = " <<a<< std::endl;   //accessing member variables of class One
            std::cout << "Value of b = " <<b<< std::endl;    //accessing member variables of class Two
            std::cout << "Value of c = " <<a+b<< std::endl;
        }
        
    };
    int main() 
    {    
        Main main;
        main.getinfoOne(10);  //accessing member function of class One
        main.getinfoTwo(20);  //accessing member function of class Two
        main.Display();
         
        return 0; 
    }

    Output:

    Value of a = 10

    Value of b = 20

    Value of c = 30

     

    Hybrid Inheritance in C++

    At this point, we have a good understanding of all types of inheritance used in C++. But, wait what if we want to use 2 different types of inheritance? Is it possible? Yes, it is possible with the help of hybrid Inheritance. In hybrid Inheritance, we combine 2 different types of inheritance. For example- Multilevel and multiple inheritance, Hierarchical and multiple inheritance, etc.hybrid

    #include <iostream> 
    using namespace std; 
      
      class World{
          protected:
          int a;
          public:
          void getinfoWorld(int x){
              a = x;
          }
           };
    class Continent : public World{
        protected:
        int b;
        public:
        void getinfoContinent(int y){
            
            b = y;
        }
        
    };
    
    class Country{
        protected:
        int d;
        public:
        void getinfoCountry(int m){
            
            d = m;
        }
    };
    
    class Australia : public Continent, public Country {
        
        public : 
            void Display(){
            std::cout << "Value of a = " <<a<< std::endl;   //accessing member variables of class One
            std::cout << "Value of b = " <<b<< std::endl;    //accessing member variables of class Two
            std::cout << "Value of c = " <<a+b<< std::endl;
            std::cout << "Value of d = " <<d<< std::endl;
            
        }
        
    };
    int main() 
    {    
        Australia australia;
        australia.getinfoWorld(10);    //accessing member function of class World
        australia.getinfoContinent(20);  //accessing member function of class Continent
        australia.getinfoCountry(40);  //accessing member function of class Country
        australia.Display();            //accessing member function of class Australia
         
        return 0; 
    }

    Output:

    Value of a = 10

    Value of b = 20

    Value of c = 30

    Value of d = 40

     

    The Diamond Problem

    Hybrid Inheritance comes with an ocean of possibilities and also brings a bucket of problems with it. There’s a popular problem called the diamond problem in C++ it is a result of ambiguity created because of Hybrid Inheritance.

    Diamond-problem

    Let’s understand the above diagram which will help us in understanding the diamond problem. class B and class C inherits from class A hence both class A and class B have attributes and methods of class A. if class D inherits from Class B as well as class C. class D will have all the attributes of class B and class C. It also has all the attributes of class A inherited from class B as well as class C. hence if we make an object of class D and call a method of class A. an ambiguous situation will be created and compiler will be confused from where it should class method of A, from class B or class D.

    To solve this ambiguity we use a concept called the virtual base class. When we make a base class a virtual base class only one copy of that class is inherited regardless of the number of existing paths between the virtual base class and a derived class.

    class A{
    
    
    };
    class B: virtual public A{
    
    
    };
    class C: virtual public A{
    
    
    };
    class D: public C, public D{
    
    
    };

    With this, we come to an end of this Inheritance in C++ article.  If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

    Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

    Comments
    0 Comments

    Browse Categories

    Subscribe to our Newsletter, and get personalized recommendations.