Introduction
Inheritance is the process of including data member and member functions( or attributes) of one class in other. This enables us to access protected and public sections of one class in other. In object oriented programming like C++, the concept of inheritance plays an important role.
We cannot access the private members of the class through inheritance.
In inheritance concept, we learn about two types of classes :-
Base Class
The class from which we access the various attributes is called base class. It is also called super class or parent class.
Derived Class
The class accessing or including attributes from the base class is called derived class. It is also known as subclass or child class.
For example: If class B inherits attributes from another class A then, A is base class and class B is derived one.
Syntax:
Here, the derived class B has inherited the protected and public members of class A under its public section. To inherit these attributes in the private section, just replace private with public i.e. 'class B : private A'.
Types of Inheritance
1. Single Level Inheritance
The inheritance in which a derived class inherit from one base class is called single inheritance.
2. Multi Level Inheritance
If the derived class inherits members from a class which has inherited attributes from another base class, then this type of inheritance is referred to as multi level inheritance.
3. Multiple Inheritance
When a class inherits attributes from more than one base class, then it is called multiple inheritance.
4. Hierarchical Inheritance
Hierarchical inheritance is when a base class has more than one subclass ( or derived class). In other words, when many subclasses inherit attributes from same base class, then it is called hierarchical inheritance. Thus, it can be comprehended as opposite of multiple inheritance.
5. Hybrid Inheritance
As its name suggests, hybrid inheritance is a combination of all the above types of inheritance. In this, a mixed relations between various derived classes and base classes are observed. A superclass can have many subclass which can be base class of others which, further, can have same or different derived classes. Got confused, no problem. Just understand that it is a typical example of hybrid inheritance which includes single, multi, multiple and hybrid inheritance.
Importance of Inheritance
We can define one class in terms of other.
It is possible to access various functionalities of parent class, together with additional objects, in child class.
It allows us to simplify the code by reducing and reusing it.