Inheritance in cpp is one of the important features in object oriented programming.
In this tutorial we are going to see what is inheritance, its types and advantages of inheritance.
Lets see inheritance definition.
What is Inheritance
Inheritance means deriving one class from another class. Deriving class is called as Bas e class or parent class and derived class is known as child or derived class.
It supports reusability.
Inheritance is basically used to allow functions and variables of one class to be used in another.
It is to make most of the code already written. It saves time and is efficient.
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hybrid Inheritance
5. Hierarchical Inheritance
What is the use of Inheritance
Suppose you want to store name and number of teachers of different subject. then what we will do we simply write different class for subject and take a name and number input in every class as shown below
Instead of writing different function in every class we create one common class in which we write function and inherit that class for every subject class. Inheritance allows access to data member of class to other class. so we use following approach which is known as re usability of code.
Advantages of Inheritance :
1. It Allows the code to be reused as many times as needed.
2. Saves time and effort as the main code need not be written again.
Visibility Modes in Inheritance
There are three visibility modes present in c++.
In this visibility mode private data can be access only in class.
They cannot access outside of the class means the non members function and outside the function .not even in main function.
In this visibility mode protected data can be accessed in the same class and also in derived class and cannot be accessed by the other function , not even main.
In this visibility mode public data can be accessed by in same class as well as in other member function. public data can be accessed anywhere.