It is a great feeling if we could reuse anything which we bought or created. In the same way it is good to reuse the class which we have created earlier in a program. Object Oriented Programming provides this feature which is called as Inheritance. The main concept of Inheritance is re-usability i.e. using the data members and member function of a class in other class.
Let us learn about different types of Inheritance in detail in this session. There are five types of Inheritance.
- Single Inheritance
- Multilevel Inheritance
- Multiple Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Before learning how to do Inheritance we need to know about basic terminology. First one is Base class, Base class is one which being inherited. i.e. the features of base class are used in other class using inheritance. The class which is made from the features of base class and contains it’s own features is called as derived class.
Syntax: The syntax for inheriting a class is
class class_name: visibility base_class_name;
By using above syntax we can declare a class which uses the features of other classes. In the syntax we need to specify the visibility of the members of the base class. There are three types of visibility modes they are public, protected, Private. We know the meaning of using these modes for data members and member functions. Here also they play the same role but with little complexity. Remember that we can’t inherit private data members of base class.
*If we use the mode as public then those members which are public in base class will become public in derived class and can be used in main method. Those members which are in protected mode will be in the same mode.
*If we use the mode as protected then those members which are in public and protected mode will be protected in derived class and can’t be accessed in the main method. .
*If we use the mode as private then all the members irrespective of their mode in base class will become private in the derived class.
Single Inheritance: If a base class is being inherited by only one derived class then it is known as single inheritance. Then the derived class contains features of base class and derived class. Therefore we access base class data members and member functions using derived class objects. Consider a small program where do single inheritance.
#include iostream.h #include conio.h class parent { public: int x; int y; }; class child: public parent { public: int sum; }; void main() { clrscr(); child ob; ob.x=5; ob.y=10; ob.sum=ob.x+ob.y; cout<<"Sum of two numbers is:"<<ob.sum; }
Here parent is the base class and child is the derived class.There fore the child class cointains the data members x, y in addition to it’s data member sum.
We shall continue about inheritance in next class.